Last updated: Jan 26, 2024
Reading timeยท2 min

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.

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:

We get an error message:
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, }, });
You can learn more about the related topics by checking out the following tutorials: