AWS CloudFormation: DeletionPolicy Overview
- What is DeletionPolicy?
- A property in AWS CloudFormation templates that determines the fate of a resource when it's removed from the template or when the stack is deleted.
- Allows for preservation and backup of resources.
- Default Behavior
- By default, all resources are deleted when a CloudFormation stack is deleted (
DeletionPolicy is Delete).
- This default policy does not need to be explicitly stated in the template.
- DeletionPolicy: Delete
- When set to
Delete, the resource will be removed along with the stack deletion.
- For S3 buckets, the
Delete policy will only work if the bucket is empty. If not, the deletion will fail.
- To delete a non-empty S3 bucket, you must either:
- Manually remove all contents before deletion.
- Use a custom resource to empty the bucket before deletion.
- DeletionPolicy: Retain
- When set to
Retain, the specified resource will not be deleted even if the stack is removed.
- Useful for preserving data, such as in a DynamoDB table.
- DeletionPolicy: Snapshot
- This policy creates a final snapshot of the resource before deletion.
- Supported by resources like EBS volumes, ElastiCache clusters, RDS instances, and more.
- Ensures data backup and safety before resource deletion.
Example Scenario
- Template File:
deletionpolicy.yaml
- Contains a security group with
DeletionPolicy: Retain.
- It contains an EBS volume with a
DeletionPolicy: Snapshot.
- Stack Creation and Deletion
- A stack named
DeletionPolicyDemo is created with the above resources.
- Upon deletion:
- The security group is retained (DeletionPolicy: Retain).
- The EBS volume is deleted, but a snapshot is created (DeletionPolicy: Snapshot).
- Manual Cleanup Required
- The retained security group must be manually deleted if no longer needed.
- The created snapshot should also be manually deleted for full cleanup.
Conclusion
- The
DeletionPolicy attribute is a powerful tool for managing resource lifecycles in AWS CloudFormation.
- It controls resource preservation, automated backups, and clean resource removal.
- Users must know the manual steps required when using
Retain and Snapshot policies for complete stack cleanup.
You cannot delete stacks that have termination protection enabled. If you attempt to delete a stack with termination protection enabled, the deletion fails, and the stack - including its status - remains unchanged. Disable termination protection on the stack, then perform the delete operation again.