Course contentsShow
← Cloud and Infrastructure
Lesson 852 of 2,98916. AWS CloudFormationFree lesson

Stack Deletion and Retention Policies

Understand stack deletion behavior, DeletionPolicy attribute, and how to retain resources after stack removal.

Stack Deletion and Retention Policies

What you'll learn: How to control what happens to your AWS resources when you delete a CloudFormation stack, including how to protect critical data from accidental deletion.

The Problem with Default Deletion

When you delete a CloudFormation stack, AWS's default behavior is to delete all the resources defined in that stack's template. This is like demolishing an entire building when you decide you don't need the construction blueprint anymore—everything goes, including potentially valuable data like databases, storage buckets, or logs.

The DeletionPolicy Attribute

CloudFormation provides the DeletionPolicy attribute to give you fine-grained control over what happens to individual resources during stack deletion. Think of it as a "last will and testament" for each resource in your template.

You can set three different policies:

  • Delete (default): The resource is deleted when the stack is deleted
  • Retain: The resource is preserved and remains in your AWS account even after stack deletion
  • Snapshot: (For supported resources like RDS, EBS) Creates a backup snapshot before deletion

When to Use Retention Policies

Use Retain for resources containing important data or state you might need later:

Resources:
  MyProductionDatabase:
    Type: AWS::RDS::DBInstance
    DeletionPolicy: Retain
    Properties:
      # ... database configuration

Use Snapshot when you want a backup but don't need the resource itself:

  MyDataVolume:
    Type: AWS::EC2::Volume
    DeletionPolicy: Snapshot

Key Takeaway: The DeletionPolicy attribute protects critical resources from accidental deletion when removing CloudFormation stacks—always set Retain or Snapshot for resources containing valuable data.