S3 bucket is not removed by CDK destroy
For example, my CDK project has S3 bucket, IAM role, and Lambda function.
$ cdk bootstrap
$ cdk deploy
This creates an S3 bucket, IAM role, and Lambda function.
$ cdk destroy
It removes the IAM role and Lambda function but the S3 bucket is retained.
Of course, the S3 bucket is empty.
Is this the correct behavior? if so, which resources will be retained other than S3 buckets?
Solution 1:
The bucket is retained due to its RetentionPolicy. From the CDK documentation on RetentionPolicy:
The removal policy controls what happens to the resource if it stops being managed by CloudFormation.
Name | Description |
---|---|
DESTROY | This is the default removal policy. |
RETAIN | This uses the 'Retain' DeletionPolicy, which will cause the resource to be retained in the account, but orphaned from the stack. |
SNAPSHOT | This retention policy deletes the resource, but saves a snapshot of its data before deleting, so that it can be re-created later. |
Regarding your question on which resources will be retained:
Many stateful resources in the AWS Construct Library will accept a removalPolicy as a property, typically defaulting it to RETAIN.
Typically, this includes resources like S3 Buckets, Database resources, etc.
From AWS CDK documentation for S3 Buckets:
removalPolicy?
Type: RemovalPolicy (optional, default: The bucket will be orphaned.)
The overview page also has more details.