How to enable Termination Protection on a CDK stack

Borislav Hadzhiev

Last updated: Jan 26, 2024
2 min


# Enabling termination protection on a CDK stack

Termination protection is a CloudFormation feature that helps prevent 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).

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.

import * as cdk from 'aws-cdk-lib'; import * as s3 from 'aws-cdk-lib/aws-s3'; 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 the destroy command.

npx aws-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, }, });

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev