''cdk destroy' is not working as intended or I am not understanding it correctly?

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?



Solution 1:[1]

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.

Solution 2:[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

Solution 3:[3]

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

Solution 4:[4]

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

Solution 5:[5]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 woodykiddy
Solution 2 Rustem Zinnatullin
Solution 3 wprl
Solution 4 Constantin De La Roche
Solution 5 mtk