How to properly delete with AWS CDK
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In cloud computing, effective management of resources is crucial to ensure efficient use of infrastructure and cost savings. The AWS Cloud Development Kit (AWS CDK) allows developers to define their cloud resources using familiar programming languages, enabling infrastructure as code (IaC). However, with IaC comes the responsibility to manage resource lifecycles, including deletion. This article focuses on how to properly delete resources using AWS CDK, providing detailed technical explanations and examples where relevant.
Understanding AWS CDK Deletion
With AWS CDK, deletion of resources is primarily controlled through the lifecycle policies of the underlying AWS resources. Understanding these policies is critical for ensuring that resources are deleted when no longer needed and that they do not inadvertently accrue charges.
Lifecycle Policies
AWS enables control over the lifecycle of resources through several attributes, mainly:
- DeletionPolicy (CloudFormation resource): This policy determines what happens to the resource when its corresponding AWS CDK stack is deleted. The policy can be set to:
- Retain: The resource is kept even after the stack is deleted.
- Delete: The resource is deleted when the stack is deleted.
- Snapshot: A snapshot of the resource is created before the resource itself is deleted.
- UpdateReplacePolicy: Similar to DeletionPolicy, this policy controls the behavior of resources during update operations that require replacement.
The Default Behavior
By default, when a stack is deleted, AWS CloudFormation deletes its resources. However, certain resources such as databases and S3 buckets might require explicitly setting the DeletionPolicy to ensure they are deleted per your requirements.
How to Delete Resources Using AWS CDK
To delete resources using AWS CDK, follow these steps:
- Define the Stack: Create a construct defining your stack in AWS CDK. For instance:
- Automation and Testing: Employ automated tests (e.g., using Jest with constructs like
@aws-cdk/assert) to verify that resource deletion behavior conforms to expectations. - Version Control: Keep AWS CDK code in version control to track infrastructure changes reliably.
- Cost Management: Regularly audit unused resources and ensure their correct deletion to prevent unexpected charges.

