How to Delete a CDK Stack in AWS CDK

avatar

Borislav Hadzhiev

Thu Apr 14 20222 min read

banner

Photo by Bogdan Pasca

Updated - Thu Apr 14 2022

Deleting a CDK Stack #

In order to delete a CDK stack, we have to use the cdk destroy command.

shell
npx aws-cdk destroy

If we have more than 1 stack in our CDK app, we have to explicitly specify the name of the stack we want to delete.

For example, the following command deletes both my-stack-dev and my-stack-prod stacks:

shell
npx aws-cdk destroy my-stack-dev my-stack-prod

Stateful Resources don't get deleted by default #

By default stateful resources (S3 buckets, databases), don't get deleted when we delete a CDK stack. Instead they remain in our account in an orphaned state.
The code for this article is available on GitHub

For example, if we want to change the default behavior for an S3 bucket, we have to specify the removalPolicy and autoDeleteObjects props when instantiating the construct:

lib/cdk-starter-stack.ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as s3 from 'aws-cdk-lib/aws-s3'; import * as cdk from 'aws-cdk-lib'; 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, 'avatars-bucket', { // 👇 set removalPolicy to DESTROY removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true, }); } }

In the code snippet:

  1. We have defined an S3 Bucket using the Bucket construct

  2. We set the bucket's removalPolicy property to DESTROY, which means that if the bucket is empty when we delete the CDK stack, the bucket will also get deleted.

    In order to delete the bucket even if it's not empty, we set the autoDeleteObjects prop to true. This will take care of emptying the bucket before deleting it.

The default removalPolicy for stateful resources (S3 buckets, databases) is RemovalPolicy.RETAIN, which causes the resources to remain in our account even after we've deleted the CDK stack.

The same example, but with a Dynamodb table looks like:

lib/cdk-starter-stack.ts
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; import * as s3 from 'aws-cdk-lib/aws-s3'; import * as cdk from 'aws-cdk-lib'; export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps) { super(scope, id, props); const table = new dynamodb.Table(this, 'my-table', { partitionKey: {name: 'todoId', type: dynamodb.AttributeType.NUMBER}, // 👇 set removalPolicy to DESTROY removalPolicy: cdk.RemovalPolicy.DESTROY, }); } }

If the removal policies of our stateful resources have been set to DESTROY, the cdk destroy command will completely clean up the resources our stack provisions.

Further Reading #

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