Sub topic 13
Removal policies and protecting stateful resources
This chapter explains what happens to a resource when its stack is deleted or the resource is replaced. It assumes you can define an S3 bucket and a Lambda function in a CDK stack and run cdk deploy and cdk destroy. It also assumes you know what CloudFormation stacks and logical IDs are.
Why removal behavior matters
A stack is a unit of creation and deletion. When you run cdk destroy, CloudFormation deletes every resource in the stack. For a Lambda function this is harmless, because you can redeploy it from code. For an S3 bucket full of uploads or a database full of orders, deletion destroys data that your code cannot recreate.
CloudFormation handles this with a deletion policy, an attribute on each resource. The CDK exposes it as a removal policy. You set it in code, and the CDK writes the matching DeletionPolicy and UpdateReplacePolicy attributes into the template.
The three removal policies
The RemovalPolicy enum has three values.
| CDK value | CloudFormation result | What happens on stack deletion |
|---|---|---|
| `RemovalPolicy.DESTROY` | `Delete` | The resource is deleted. |
| `RemovalPolicy.RETAIN` | `Retain` | The resource is left in your account, but no longer belongs to the stack. |
| `RemovalPolicy.SNAPSHOT` | `Snapshot` | A snapshot is taken, then the resource is deleted. Only some resource types support this, such as RDS databases and EBS volumes. |
The CDK also has RETAIN_ON_UPDATE_OR_DELETE, which keeps the resource when it is deleted and when an update would replace it. Check that your construct library version supports it before relying on it.
If you set nothing, the default depends on the construct. Most L2 constructs for stateful resources, including s3.Bucket and dynamodb.Table, default to RETAIN. Other constructs differ. For example, a CloudWatch log group created by logs.LogGroup defaults to RETAIN as well, but some resources default to DESTROY. Read the construct's API reference instead of guessing, and set the policy explicitly on any resource that holds data.
Retain is not the same as safe
Setting RETAIN on a bucket has these consequences:
- The bucket survives
cdk destroy. It is no longer managed by any stack. - The bucket still costs money, and it still holds its objects.
- Its name stays taken. If you redeploy the stack with a fixed bucket name, creation fails because the name already exists.
For that reason, avoid hard-coding physical names such as bucketName: 'uploads'. Let the CDK generate a name from the construct path and a hash. A generated name avoids collisions between environments and between a retained bucket and its replacement.
Replacement and UpdateReplacePolicy
Deletion is not the only danger. Some property changes force CloudFormation to replace a resource: it creates a new one, then deletes the old one. A change to a DynamoDB table's key schema works this way, and so does a change to a bucket's name. CloudFormation controls what happens to the old resource through UpdateReplacePolicy.
The CDK sets UpdateReplacePolicy to match your removal policy. With RETAIN, the old bucket survives a replacement, though the new one starts empty. With DESTROY, the old data is gone as soon as the replacement succeeds.
Run cdk diff before every deploy. A replacement appears in the diff with [-] and [+] markers and a replace note on the property that forced it. Stop and read these carefully for any stateful resource.
Setting a policy in code
The following TypeScript stack protects a production table and allows a scratch bucket to be deleted.
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);
const orders = new dynamodb.Table(this, 'Orders', {
partitionKey: { name: 'orderId', type: dynamodb.AttributeType.STRING },
billingMode: dynamodb.BillingMode.PAY_PER_REQUEST,
pointInTimeRecovery: true,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
const scratch = new s3.Bucket(this, 'ScratchBucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
autoDeleteObjects: true,
});
new cdk.CfnOutput(this, 'OrdersTableName', { value: orders.tableName });
new cdk.CfnOutput(this, 'ScratchBucketName', { value: scratch.bucketName });
}
}
const app = new cdk.App();
new DataStack(app, 'DataStack');Here is the same pattern in Python.
from aws_cdk import App, CfnOutput, RemovalPolicy, Stack
from aws_cdk import aws_dynamodb as dynamodb
from aws_cdk import aws_s3 as s3
from constructs import Construct
class DataStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
orders = dynamodb.Table(
self,
"Orders",
partition_key=dynamodb.Attribute(
name="orderId", type=dynamodb.AttributeType.STRING
),
billing_mode=dynamodb.BillingMode.PAY_PER_REQUEST,
point_in_time_recovery=True,
removal_policy=RemovalPolicy.RETAIN,
)
scratch = s3.Bucket(
self,
"ScratchBucket",
removal_policy=RemovalPolicy.DESTROY,
auto_delete_objects=True,
)
CfnOutput(self, "OrdersTableName", value=orders.table_name)
CfnOutput(self, "ScratchBucketName", value=scratch.bucket_name)
app = App()
DataStack(app, "DataStack")
app.synth()Why a bucket needs autoDeleteObjects
CloudFormation cannot delete a bucket that still contains objects. With DESTROY alone, cdk destroy fails on a non-empty bucket and leaves the stack in a DELETE_FAILED state.
Setting autoDeleteObjects: true adds a custom resource, a Lambda function that empties the bucket just before deletion. The CDK only allows this option together with RemovalPolicy.DESTROY. This is also why a bootstrapped environment matters: the helper's code is delivered as an asset.
Use autoDeleteObjects only for disposable data such as test environments, since it permanently deletes every object.
Applying a policy to a whole subtree
You can also set a policy after the fact with applyRemovalPolicy, which every resource supports. It applies to the resource you call it on, including L1 constructs.
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as sqs from 'aws-cdk-lib/aws-sqs';
export class QueueStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const queue = new sqs.Queue(this, 'Jobs');
queue.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN);
}
}A common team convention is to write a small Aspect that sets DESTROY on every stateful resource in development stacks and leaves production alone. The later chapter on aspects covers that mechanism.
Protecting a stack as a whole
Removal policies guard individual resources. Two other controls guard the stack:
- Termination protection makes
cdk destroyand the CloudFormation delete call fail until you turn it off. SetterminationProtection: truein the stack props. - Stack policies and IAM permissions can deny deletion for certain principals. Use them in shared accounts where many people can run deployments.
import * as cdk from 'aws-cdk-lib';
const app = new cdk.App();
new cdk.Stack(app, 'ProdDataStack', {
terminationProtection: true,
});Common errors
- Orphaned resources after destroy. A
RETAINresource stays in the account. Delete it by hand when you no longer need it, or you keep paying for it. - "Bucket already exists" on redeploy. A retained bucket holds a fixed name. Remove the explicit name, or delete the old bucket.
DELETE_FAILEDon a bucket. The bucket is not empty andautoDeleteObjectsis off.- Changing a logical ID. Renaming a construct ID, or moving it in the tree, changes its logical ID. CloudFormation then sees one resource removed and another added. With
DESTROYthis deletes your data. Checkcdk diffafter every refactor. - Assuming defaults. Do not rely on a default. State the policy for each stateful resource.
Exercises
Exercise
You set removalPolicy: RemovalPolicy.DESTROY on an S3 bucket that contains files, then run cdk destroy. The stack ends in DELETE_FAILED. What is the cause, and what is the CDK option that fixes it for a disposable bucket?
Show answer
CloudFormation cannot delete a bucket that still holds objects. For a disposable bucket, add autoDeleteObjects: true (Python: auto_delete_objects=True), which installs a custom resource that empties the bucket before deletion. It only works with RemovalPolicy.DESTROY.
Exercise
A teammate renames the construct ID of a DESTROY DynamoDB table from Orders to OrdersTable during a refactor. What does CloudFormation do on the next deploy, and how do you catch it first?
Show answer
The logical ID changes, so CloudFormation creates a new empty table and deletes the old one, which loses the data. Run cdk diff before deploying. It shows the old table removed and a new one added. Use RETAIN on stateful resources so the old table survives either way.