How to Delete an S3 bucket on CDK destroy

avatar

Borislav Hadzhiev

Last updated: Apr 13, 2022

banner

Photo from Unsplash

Deleting S3 Buckets on CDK Destroy #

In order to delete an S3 bucket on CDK destroy, we have to set its RemovalPolicy to DESTROY:

const s3Bucket = new s3.Bucket(this, 'my-bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, });

With this configuration the bucket will be deleted as long as it is empty.

If we try to delete a bucket that's not empty, we would get an error:

The bucket you tried to delete is not empty

The automated way to empty the bucket before deleting it is to set the autoDeleteObjects property to true:

const s3Bucket = new s3.Bucket(this, 'my-bucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true, });

Wth the autoDeleteObjects property we specify if all of the objects stored in our s3 bucket should be automatically deleted when the bucket is removed from our stack or when the stack itself is destroyed.

We can only set the autoDeleteObjects property to true, if the removalPolicy property is set to DESTROY.

By setting the autoDeleteObjects property to true, CDK will provision a Lambda function for us that will automatically delete all of the bucket's objects prior to deleting the bucket.

orphaned s3 bucket

The second resource in the screenshot is the lambda function that CDK automatically provisioned for us, it simply empties the bucket's contents.

Discussion #

When we delete a CDK stack by issuing the npx aws-cdk destroy my-stack command any stateful resources, i.e. s3 buckets and databases are left orphaned.

It's the same if we remove an S3 bucket resource from a CDK stack, it will still remain in our account(in an orphaned state).

The default behavior for the AWS S3 construct is that the removalPolicy property is set to RETAIN:

const s3Bucket = new s3.Bucket(this, 'my-bucket', { removalPolicy: cdk.RemovalPolicy.RETAIN, });

The default behavior of retaining s3 buckets and databases on stack deletion is what we want most of the time, however, it's nice of the CDK team to supply us with an easy way to opt out.

By setting the bucket's removalPolicy to DESTROY and setting the autoDeleteObjects property to true we were able to empty a bucket's contents and delete it when the stack is deleted.

Further Reading #

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.