Search code examples
typescriptamazon-ec2aws-cdkaws-auto-scaling

How do you run commands on ASG EC2 instance start from AWS CDK


How can I add commands to run on instance start when using AWS CDK (Typescript)


Solution

  • You can use asg.userData.addCommands(...commands);

    Example below:

    /**
     * Auto-scaling group
     */
    const asg = new autoscaling.AutoScalingGroup(this, 'ASG ' + STAGE, {
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T3, ec2.InstanceSize.MEDIUM),
      keyName: 'my_key',
      machineImage: ec2.MachineImage.genericLinux({ 'eu-west-1': 'your_ami' }),
      updateType: autoscaling.UpdateType.REPLACING_UPDATE,
      minCapacity: 2,
      maxCapacity: 10,
      maxInstanceLifetime: cdk.Duration.days(14),
      vpcSubnets: {
        subnetType: ec2.SubnetType.PUBLIC,
      },
      securityGroup: ec2SecurityGroup,
      vpc,
    });
    
    /**
     * Commands to run on instance init
     * Git pull and npm start
     * Needs to be run as ec2-user not root
     */
    const commands = [`runuser -l  ec2-user -c 'cd /home/ec2-user/source && git pull && npm start'`];
    
    asg.userData.addCommands(...commands);