如何通过CloudFormation将弹性IP从一个EC2实例切换到另一个
如何通过CloudFormation在不删除旧实例的情况下切换弹性IP到新实例?
可行,核心思路是让旧弹性IP脱离原栈的管理,再将其关联到新栈的实例上,全程可通过CloudFormation命令和模板调整完成,无需手动操作EIP关联。
步骤1:调整旧栈,解除EIP与旧实例的关联并保留EIP
原栈ec2-example管理着目标EIP和它与旧实例的关联,首先需要更新旧栈,移除关联关系同时保留EIP资源:
- 修改旧栈的模板(比如命名为
updated-old-template.yaml):- 删除
EIPAssociation资源 - 给
myEIP资源添加DeletionPolicy: Retain,确保后续操作不会误删该EIP
修改后的关键片段如下:
Resources: myENI: Type: AWS::EC2::NetworkInterface Properties: SubnetId: <subnet-id> Instance: Type: AWS::EC2::Instance Properties: ImageId: <ami-id> InstanceType: t2.micro NetworkInterfaces: - NetworkInterfaceId: !Ref myENI DeviceIndex: '0' Tags: - Key: Name Value: test-instance-1 myEIP: Type: AWS::EC2::EIP DeletionPolicy: Retain Properties: Domain: vpc - 删除
- 执行旧栈更新命令:
完成后,旧EIP会与旧实例的ENI解除关联,且仍保留在AWS账户中,不再受旧栈的关联管理。aws cloudformation update-stack --stack-name ec2-example --template-body file://updated-old-template.yaml
步骤2:获取旧EIP的AllocationId
执行以下命令获取目标EIP(35.82.18.137)的分配ID:
aws ec2 describe-addresses --public-ips 35.82.18.137 --query 'Addresses[0].AllocationId' --output text
记录下返回的分配ID(比如eipalloc-xxxxxxx)。
步骤3:更新新栈,关联旧EIP到新实例
修改新栈的模板(比如命名为updated-new-template.yaml),移除自动创建EIP的逻辑,改为引用旧EIP的AllocationId:
- 添加参数接收旧EIP的AllocationId,同时删除
myEIP资源,调整EIPAssociation的配置:AWSTemplateFormatVersion: 2010-09-09 Description: Testing stuff Parameters: OldEIPAllocationId: Type: String Description: Allocation ID of the existing EIP to associate with the new instance Resources: myENI: Type: AWS::EC2::NetworkInterface Properties: SubnetId: <subnet-id> Instance: Type: AWS::EC2::Instance Properties: ImageId: <ami-id> InstanceType: t2.micro NetworkInterfaces: - NetworkInterfaceId: !Ref myENI DeviceIndex: '0' Tags: - Key: Name Value: test-instance-2 EIPAssociation: Type: AWS::EC2::EIPAssociation Properties: AllocationId: !Ref OldEIPAllocationId NetworkInterfaceId: !Ref myENI DependsOn: Instance - 执行新栈更新命令,传入旧EIP的AllocationId参数:
完成后,CloudFormation会自动将旧EIP关联到新实例的ENI上,旧实例则不再持有该EIP。aws cloudformation update-stack --stack-name ec2-example-1 --template-body file://updated-new-template.yaml --parameters ParameterKey=OldEIPAllocationId,ParameterValue=<旧EIP的AllocationId>
注意事项
- 确保旧EIP的
Domain属性为vpc(与新实例的网络环境匹配),你的旧EIP已经符合这个要求。 - 若后续需要删除旧栈,
DeletionPolicy: Retain会保证旧EIP不会被删除,避免资源丢失。
内容的提问来源于stack exchange,提问作者Somethingwhatever
相关产品推荐
相关产品推荐

