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

To delete a CDK stack, we have to use the cdk destroy command.
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.
npx aws-cdk destroy my-stack-dev my-stack-prod
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.
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 sample:
We have defined an S3 Bucket using the Bucket construct.
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.
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 as follows.
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.
You can learn more about the related topics by checking out the following tutorials: