使用AWS CDK创建ASG时,如何将Launch Configuration改为Launch Template?
将AWS CDK中的Auto Scaling Group从Launch Configuration切换为Launch Template
为什么会生成Launch Configuration?
你当前使用的autoscaling.AutoScalingGroup构造默认会自动创建Launch Configuration(LC),这是旧版的实例配置方式。AWS已停止为LC添加新EC2特性支持,因此需要切换到Launch Template(LT)。
修改后的CDK代码
要切换到Launch Template,需先显式创建autoscaling.LaunchTemplate实例,再将其关联到Auto Scaling Group中。修改后的代码如下:
// 1. 创建Launch Template,存放实例配置参数 const launchTemplate = new autoscaling.LaunchTemplate(this, 'MyAppLaunchTemplate', { launchTemplateName: `myapp-${targetEnv}-lt`, instanceType: new ec2.InstanceType('t2.medium'), machineImage: ecs.EcsOptimizedImage.amazonLinux(), securityGroup: instanceSg, keyName: "ssh-test" }); // 2. 基于Launch Template创建Auto Scaling Group const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', { vpc, autoScalingGroupName: `myapp-${targetEnv}-asg`, launchTemplate: launchTemplate, // 关联Launch Template minCapacity: 1, maxCapacity: 3 }); // 3. 保留原有的Capacity Provider配置 const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', { autoScalingGroup, capacityProviderName: `myapp-${targetEnv}-cp` }); cluster.addAsgCapacityProvider(capacityProvider);
关键改动说明
- 把原ASG中的
instanceType、machineImage、securityGroup、keyName等实例配置参数,迁移到LaunchTemplate构造中 - ASG通过
launchTemplate属性关联新创建的Launch Template,不再依赖旧的实例配置参数 - 部署后,AWS会生成对应的Launch Template,Auto Scaling Group将基于它管理EC2实例,不再创建Launch Configuration
内容的提问来源于stack exchange,提问作者whitebear
相关产品推荐
相关产品推荐

