How can I enable termination protection for an EC2 Instance managed by the CDK, and still allow the CDK to terminate it in order to replace it?



We have had a PEN test requirement to enable termination protection on all our EC2 instances.

We have bastion instances managed by the CDK. We fulfilled this requirement as so:

var bastion = BastionHostLinux.Builder.create(...).build();
var cfnBastion = (CfnInstance) bastion.getNode().getDefaultChild().getNode().getDefaultChild();

However, now whenever a new kernel is released the CDK provisions a new bastion instance, and then tries and fails to terminate the old one - because it has termination protection enabled.

Is there any hook that will let the CDK disable termination protection when it wants to decommission an instance it is managing?

1 Answer


The way to do it is to have IAM policies denying ec2:TerminateInstances explicitly to all security principals (or least not allowing it directly or indirectly via Action:*) except the execution role of the CDK.

See for all possible EC2 auths.

So, nobody except CDK (and global Admin) will then be allowed to terminate EC2 instances.

The Termination Protection feature does not relate to IAM: it's either all (lncl. your CDK role) or nothing. So, you have to revert to IAM policies to achieve your goal.



profile pictureAWS
answered 7 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