How to enable Termination Protection on a CDK stack

avatar

Borislav Hadzhiev

Sat Apr 24 20212 min read

Updated on Sat Apr 24 2021

Enabling termination protection on a CDK stack #

Termination protection is a CloudFormation feature that helps prevent an accidental stack deletion.

Since our CDK code gets compiled down to CloudFormation before a deployment, we can take advantage of this feature.

If a user tries to delete a stack with enabled termination protection they get an error and the delete operation fails.

Note that if we enable termination protection on a stack, the feature gets enabled for all nested stacks (if any are present).

In order to enable termination protection for a CDK stack we have to set the terminationProtection prop to true when creating the stack.

const app = new cdk.App(); new MyCdkStack(app, 'my-cdk-stack', { stackName: 'my-cdk-stack', // ๐Ÿ‘‡ enable termination protection terminationProtection: true, env: { region: process.env.CDK_DEFAULT_REGION, account: process.env.CDK_DEFAULT_ACCOUNT, }, });

I'll cdk deploy a simple CDK stack, consisting of a single S3 bucket to demonstrate the result.

export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps) { super(scope, id, props); const s3Bucket = new s3.Bucket(this, id, { removalPolicy: cdk.RemovalPolicy.DESTROY, }); } }

Let's take a look at the CloudFormation console after a successful deployment:

enabled protection

We can see that the termination protection feature has been enabled.

I'll now try to delete the stack by running:

shell
npx cdk destroy

The output from the command is:

destroy error

We get an error message:

Stack [my-cdk-stack] cannot be deleted while Termination Protection is enabled

This is the expected behavior - the CloudFormation stack remains and its status is unchanged.

If we decide to disable termination protection, all we have to do is flip the terminationProtection feature to false, or simply remove the property:

const app = new cdk.App(); new MyCdkStack(app, 'my-cdk-stack', { stackName: 'my-cdk-stack', // ๐Ÿ‘‡ disable termination protection terminationProtection: false, env: { region: process.env.CDK_DEFAULT_REGION, account: process.env.CDK_DEFAULT_ACCOUNT, }, });

Further Reading #

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee