9

Here is my demo stack,

export class HelloCdkStack extends cdk.Stack {
  constructor(parent: cdk.App, id: string, props?: cdk.StackProps) {
    super(parent, id, props);
    new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      encryption: s3.BucketEncryption.KmsManaged,
    });
  }
}

'cdk deploy' creates a new bucket, but when I execute 'cdk destroy' it does not delete the bucket. Am I doing anything wrong?

Neeraj
  • 2,376
  • 2
  • 24
  • 41

5 Answers5

11

By default, S3 buckets are configured to be 'orphaned' when a stack is deleted. Setting removalPolicy to Destroy will physically destroy the bucket on deletion.

woodykiddy
  • 6,074
  • 16
  • 59
  • 100
Debora Ito
  • 111
  • 2
  • Also refer to this doc: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_core.RemovalPolicy.html – woodykiddy Jul 26 '19 at 06:38
  • 5
    I think it will only delete if Destroy is set AND the bucket is empty – Tim Ker Aug 04 '19 at 04:27
  • 1
    Yes this setting will destroy the bucket, but ONLY if it is empty. A feature request for non empty buckets is being tracked here: https://github.com/aws/aws-cdk/issues/3297 – Keshav Potluri May 08 '20 at 19:02
2

You can set destroy to removalPolicy, it will remove the bucket if it's empty: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#removalpolicy

If you want to destroy even non-empty bucket, you should also set autoDeleteObjects property to true: https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#autodeleteobjects

1

If you need to automatically destroy a bucket with files in it, check out this CDK construct: https://www.npmjs.com/package/@mobileposse/auto-delete-bucket

If you need to automatically destroy a bucket that is expected to be empty, use the standard bucket and set removalPolicy to DESTROY. https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-s3.Bucket.html#removalpolicy

wprl
  • 24,489
  • 11
  • 55
  • 70
1

In my case the problem was, cdk was trying to fetch different accounts Credentials. Add the --verbose or -v flag to see if any exception is thrown internally.

It's a shame that the exception was not getting logged to stdout or stderr (as it should for any tool)

mtk
  • 13,221
  • 16
  • 72
  • 112
0

In python, following the getting started, you can add removal_policy=cdk.RemovalPolicy.DESTROY parameter when instantiate the s3.Bucket object, so the bucket will be delete on cdk destroy.

from aws_cdk import core as cdk
from aws_cdk import aws_s3 as s3


class HelloCdkStack(cdk.Stack):

    def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)
        bucket = s3.Bucket(self,
                           "MyFirstBucket",
                           versioned=True,
                           removal_policy=cdk.RemovalPolicy.DESTROY)  # delete bucket on destroy