如何在AWS CDK部署时持久保留Elastic IP
如何让AWS CDK部署的堡垒主机Elastic IP持久保留?
我在AWS CDK中为堡垒主机配置Elastic IP的代码如下:
const eip = new ec2.CfnEIP(this, "Bast-host1") const bast_host = new ec2.BastionHostLinux(this, "myproj-Bhost", { vpc, subnetSelection: {subnetType: ec2.SubnetType.PUBLIC}, machineImage: ec2.MachineImage.latestAmazonLinux({ userData: ec2.UserData.custom('Content-Type: multipart/mixed;) }), }) new ec2.CfnEIPAssociation(this, "HostAllocation", { eip: elasticIP.ref, instanceId: bast_host.instance.instanceId });
每次部署CloudFormation堆栈时,这个Elastic IP都会被重新创建,请问有没有办法让它在每次部署时持久保留?
解决方案
问题根源
默认情况下,CloudFormation的CfnEIP资源若未配置保留策略,一旦触发资源替换逻辑(或代码存在语法/变量错误),就会被销毁重建。此外你代码中存在两处错误:变量名elasticIP应为eip,用户数据字符串未闭合引号,这些也可能导致部署异常。
方法一:为CfnEIP配置保留策略
显式设置EIP的删除和更新替换策略为RETAIN,确保堆栈更新或删除时EIP不会被销毁:
import * as cdk from 'aws-cdk-lib'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; // 创建EIP并设置保留策略 const eip = new ec2.CfnEIP(this, "Bast-host1"); eip.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN); eip.addPropertyOverride('UpdateReplacePolicy', 'Retain'); // 创建堡垒主机(修复用户数据语法错误) const bast_host = new ec2.BastionHostLinux(this, "myproj-Bhost", { vpc, subnetSelection: {subnetType: ec2.SubnetType.PUBLIC}, machineImage: ec2.MachineImage.latestAmazonLinux({ userData: ec2.UserData.custom('Content-Type: multipart/mixed;') }), }); // 关联EIP与堡垒主机(修正变量名错误) new ec2.CfnEIPAssociation(this, "HostAllocation", { eip: eip.ref, instanceId: bast_host.instance.instanceId });
方法二:使用CDK高层构造ec2.Eip(推荐)
ec2.Eip是CDK封装的高层资源,默认处理了VPC EIP的配置逻辑,使用更简洁且自带合理的保留策略:
import * as cdk from 'aws-cdk-lib'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; // 创建VPC类型的EIP const eip = new ec2.Eip(this, "Bast-host1", { vpc: true, }); // 可选:显式设置保留策略 eip.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN); // 创建堡垒主机 const bast_host = new ec2.BastionHostLinux(this, "myproj-Bhost", { vpc, subnetSelection: {subnetType: ec2.SubnetType.PUBLIC}, machineImage: ec2.MachineImage.latestAmazonLinux({ userData: ec2.UserData.custom('Content-Type: multipart/mixed;') }), }); // 关联EIP与堡垒主机 new ec2.CfnEIPAssociation(this, "HostAllocation", { eip: eip.eipId, instanceId: bast_host.instance.instanceId });
关键注意事项
- 保持EIP资源的逻辑ID(如示例中的"Bast-host1")固定,不要随意修改,否则CloudFormation会将其识别为新资源并重建。
- 修复代码中的语法错误,避免因部署异常导致的资源重复创建。
内容的提问来源于stack exchange,提问作者ShanWave007
相关产品推荐
相关产品推荐

