Delete an S3 bucket when AWS CDK stack is destroyed

Delete an S3 bucket when AWS CDK stack is destroyed - AWS CDK

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,
});

Happy coding!

Need help? Get in touch