Table of Contents
1. Introduction
I attend Coffee & Cloud: The Local Developer Experience organised by Mirabela Dan & Jason Forte on Wednesdays every fortnight.
During one of the sessions, Jason showcased Deploy a Serverless API in 30 mins.
While I was practising deploying Jason's code, I noticed that the DynamoDB was not being deleted when I ran cdk destroy
This blog is about the importance of RemovalPolicy with CDK.
2. RemovalPolicy Problem
I deployed the app using cdk deploy
and then cleaned up by using csk destroy
Upon raising this in repost:
👉 AWS advised that the table defintion was missing RemovalPolicy
.
By default, CDK will (generally) apply a RemovalPolicy value of RETAIN to stateful resources which can contain data in order to avoid deleting it when destroying the stack.
We can see this in the synthesised template. For example, with this resource declared in CDK:
const table = new Table(this, 'Table', {
partitionKey: { type: AttributeType.STRING, name: 'id' },
})
The synthesised template is under /home/ec2-user/environment/example-serverless-python-api/cdk.out/ExampleServerlessPythonApiStack.template.json
and will contain the following:
"Resources": {
"TableCD117FA1": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
...
},
"UpdateReplacePolicy": "Retain",
"DeletionPolicy": "Retain",
"Metadata": {
"aws:cdk:path": "ExampleServerlessPythonApiStack/Table/Resource"
}
},
...
Note: I am using Cloud 9
The CloudFormation UpdateReplacePolicy and DeletionPolicy attributes being Retain will cause CloudFormation to leave the resource intact when deleting the stack.
3. RemovalPolicy Solution
Let's update /example-serverless-python-api/lib/example-serverless-python-api-stack.ts
with removalPolicy: RemovalPolicy.DESTROY
const table = new Table(this, 'Table', {
partitionKey: { type: AttributeType.STRING, name: 'id' },
removalPolicy: RemovalPolicy.DESTROY,
})
👉 To have the resource deleted when we run cdk destroy
, we need to specify a RemovalPolicy of DESTROY
or SNAPSHOT
in the code.
The synthesised template under /home/ec2-user/environment/example-serverless-python-api/cdk.out/ExampleServerlessPythonApiStack.template.json
will contain the following:
"Resources": {
"TableCD117FA1": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
...
},
"UpdateReplacePolicy": "Delete",
"DeletionPolicy": "Delete",
"Metadata": {
"aws:cdk:path": "ExampleServerlessPythonApiStack/Table/Resource"
}
},
...
4. Summary
👉 Remember to add RemovalPolicy when using CDK for databases to avoid unexpected costs.
removalPolicy: RemovalPolicy.DESTROY,
Top comments (0)