How to enable Termination Protection on a CDK stack

avatar

Borislav Hadzhiev

Thu Apr 14 20222 min read

Updated - Thu Apr 14 2022

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.

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:

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

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.