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
asked 9 months ago233 views
2 Answers
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
answered 9 months ago
  • 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
EXPERT
answered 9 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions