AWS CDK

Delete an S3 bucket when AWS CDK stack is destroyed

Throwing out the garbage is just as important.

Using AWS CDK, it’s extremely easy to provision any AWS resource and then quickly drop it when you no longer needed.

CDK takes care of cleaning up after itself pretty well, but some AWS services like S3 require special “cleanup effort”, due to the fact that you can not delete an S3 bucket if it already has files inside.

This limitation cascades to the AWS CLI, the AWS Web Console, and CloudFormation.

However, the folks at AWS CDK have taken advantage of the Custom Resources framework, which basically allows you to run a Lambda every time the stack is created, updated, or deleted.

With some simple flags of the new s3.Bucket() construct, you can easily take care of deleting the S3 bucket AND the files in it, automatically, when the Bucket is destroyed.

Here’s how to achieve it:

new s3.Bucket(this, 'MyBucket', {
    removalPolicy: RemovalPolicy.DESTROY,
    autoDeleteObjects: true,
});

You are welcome, and happy coding!

Need consulting? Get in touch

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.