简体   繁体   中英

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)

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM