--
How to Apply the DeletionPolicy
You add the DeletionPolicy
attribute directly to the resource definition in your CloudFormation template.
Example 1: Retain
policy for an S3 Bucket
This example ensures that if you delete the CloudFormation stack, the MyProductionBucket
S3 bucket and its contents will not be deleted.
AWSTemplateFormatVersion: 2010-09-09
Resources:
MyProductionBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
BucketName: my-critical-production-data-bucket
Example 2: Snapshot
policy for an EBS Volume
In this example, when the stack is deleted, the EC2 instance will be terminated, but a final snapshot of MyDataVolume
will be created before the volume itself is deleted.
AWSTemplateFormatVersion: 2010-09-09
Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-0abcdef1234567890
# Other instance properties...
MyDataVolume:
Type: AWS::EC2::Volume
DeletionPolicy: Snapshot
Properties:
Size: 50
AvailabilityZone: !GetAtt MyEC2Instance.AvailabilityZone
# Other volume properties...
Best Practices Summary
-
For Production: Always use
DeletionPolicy: Retain
on critical, stateful resources like databases (RDS, DynamoDB) and S3 buckets. -
For Development/Test: The default
Delete
policy is often acceptable for ephemeral environments where you want everything to be cleaned up automatically. -
For Data You Want to Archive: Use
DeletionPolicy: Snapshot
for supported resources like EBS volumes and RDS instances if you don't need the live resource but want to keep a final backup.