Sub topic 12
Removal policies and protecting stateful resources
This chapter assumes you can define a stack with S3 and Lambda, and that you know how cdk deploy and cdk destroy work. It covers what happens to stateful resources when a stack deletes them, and how to control that.
What a removal policy does
A removal policy tells CloudFormation what to do with a resource when it is removed from a stack. A resource is removed when you run cdk destroy, delete the stack, or delete the resource from your code and redeploy. The CDK exposes this through RemovalPolicy, which has three values:
| Value | Effect on the physical resource |
|---|---|
| `RETAIN` | The resource is kept but is no longer managed by the stack. |
| `DESTROY` | The resource is deleted with the stack. |
| `SNAPSHOT` | A snapshot is taken, then the resource is deleted. Only some resources support it, such as RDS databases and EBS volumes. |
Stateless resources like a Lambda function can be recreated from code, so deleting them costs nothing. Stateful resources hold data you cannot regenerate: buckets, tables, databases, and log groups you need for audits. These are the ones to protect.
Defaults differ by construct
Most stateful L2 constructs default to RETAIN, because losing data is worse than leaving a leftover resource. Some constructs default to other behavior, and the default can change between CDK versions. Check the documentation for each construct you use. Setting the policy explicitly in your code records your intent and makes it show up in code review.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as dynamodb from 'aws-cdk-lib/aws-dynamodb';
export class DataStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
new s3.Bucket(this, 'UploadsBucket', {
versioned: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
new dynamodb.Table(this, 'ScratchTable', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
}
}The bucket survives a stack deletion. The scratch table is deleted with it, which suits a development environment.
Why DESTROY can still fail on a bucket
A non-empty S3 bucket cannot be deleted. With RemovalPolicy.DESTROY, stack deletion fails if the bucket still has objects. To have the CDK empty the bucket first, also set autoDeleteObjects: true. This adds a custom resource backed by a Lambda function that removes the objects. Use it only for disposable buckets.
Choosing a policy per environment
A common pattern is to retain data in production and clean up in development. Pass the environment name to the stack and pick the policy from it.
from aws_cdk import RemovalPolicy, Stack
from aws_cdk import aws_s3 as s3
from constructs import Construct
class DataStack(Stack):
def __init__(self, scope: Construct, construct_id: str, is_prod: bool = False, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
s3.Bucket(
self,
"UploadsBucket",
versioned=True,
removal_policy=RemovalPolicy.RETAIN if is_prod else RemovalPolicy.DESTROY,
auto_delete_objects=not is_prod,
)Retained resources have consequences
A retained resource stays in your account after the stack is gone, and you keep paying for it. If you deploy the same stack again, CloudFormation tries to create a resource with the same physical name, which fails if a retained bucket already uses that name. Letting the CDK generate names avoids most of these collisions.
Two further protections complement removal policies:
- Stack termination protection, set with
terminationProtection: truein the stack props, blocks deletion of the whole stack. - Changes that replace a resource, such as renaming its logical ID by moving it in the construct tree, delete the old one and create a new one. Run
cdk diffand look for a replacement before you deploy.
Exercise
Your development stack uses a bucket with removalPolicy: RemovalPolicy.DESTROY, but cdk destroy fails with the bucket still present. What is the likely cause and the fix?
Show answer
The bucket still contains objects, and S3 cannot delete a non-empty bucket. Set autoDeleteObjects: true on the bucket, which adds a custom resource that empties it before deletion, or empty it manually. Do this only for disposable buckets.