Delete all NIC attached to an instance on its termination

0

Hi,

We need to design a CloudFormation template that automatically delete network interfaces attached to an instance when the instance is terminated. We found a way to do it by using AWS::EC2::NetworkInterfaceAttachment (with the help of DeleteOnTermination property). But that method works only for additional NIC (second, third...) as the main NIC is created/associated at the same time as the instance creation itself (by using AWS::EC2::Instance and possibly the NetworkInterfaces property).

One other method would have been to create the instance without any NIC and attach its main NIC using the previous method (using AWS::EC2::NetworkInterfaceAttachment). But we didn't find any way to achieve that. Nor did we find a way to specify the automatic deletion when using AWS::EC2::Instance.

All suggestions would be greatly appreciated.

Best Regards, CG

profile picture
已提问 10 个月前242 查看次数
2 回答
0

Hi Didier,

Thanks for the prompt response. Actually the default value for "DeletionPolicy" is delete and NICs are already deleted when the CFN stack is deleted. What we are looking for is to delete NICS when somebody terminates an instance attached to a CFN. Any ideas?

Best Regards, CG

profile picture
已回答 10 个月前
  • Hi CG, I update my initial response with an update. It should do what you need.

0

Hi,

To achieve what you want you need to combine 2 CloudFormation features applicable to all kinds of resources that you create with your CFN template.

You have to use DependsOn to create but also in your case to destroy resources like the NICs in right order:

And you also have to you DeletionPolicy to make sure that your resources are properly deleted:

Delete is probably the option that you are looking for

Delete
CloudFormation deletes the resource and all its content if applicable during stack deletion. 
You can add this deletion policy to any resource type

Update on your response: to delete NICS when somebody terminates instance, you need to additionally configure in your CFN a Lambda triggered by the corresponding EventBridge event signalling EC2 instance termination in general. This Lambda will list the resources of the stack to which it belongs (to ensure that it acts on proper EC2 termination). If terminated EC2 is in the stack, it will then delete the NICs.

Best, Didier

profile pictureAWS
专家
已回答 10 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则