您如何从 AWS CDK 启动 ASG EC2 实例上的 运行 命令

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

如何在使用 AWS CDK (Typescript) 时在实例启动时向 运行 添加命令

您可以使用asg.userData.addCommands(...commands);

示例如下:

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