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

DeletionPolicy and Retain

Control resource lifecycle after stack deletion using DeletionPolicy attributes like Retain, Delete, and Snapshot.

DeletionPolicy and Retain

What you'll learn: How to control what happens to your AWS resources when you delete a CloudFormation stack, preventing accidental data loss.

The Problem: Deleting Stacks Can Destroy Data

By default, when you delete a CloudFormation stack, AWS destroys all the resources it created—EC2 instances, databases, S3 buckets, everything. Sometimes that's exactly what you want. But other times, you might want to preserve certain resources even after the stack is gone.

Think of it like moving out of an apartment. Usually you take everything with you (Retain), but sometimes the landlord keeps certain fixtures (Delete), or you might take photos before leaving (Snapshot).

DeletionPolicy Attributes

CloudFormation gives you three DeletionPolicy options to declare on individual resources:

Delete (default): The resource is destroyed when the stack is deleted. Use this for temporary infrastructure.

Retain: The resource is preserved after stack deletion. It becomes an orphaned resource you manage manually. Perfect for databases, S3 buckets with important data, or anything you can't afford to lose.

Snapshot: Before deletion, AWS creates a backup snapshot (works with RDS, EC2 volumes, etc.). You lose the resource but keep the data for later restoration.

When to Use Retain

Use DeletionPolicy: Retain for:

  • Production databases
  • S3 buckets with logs or user data
  • Resources shared across multiple stacks
  • Anything expensive or time-consuming to recreate

Without this protection, a single DeleteStack command could wipe out months of customer data. The Retain policy is your safety net.

Key Takeaway: Use DeletionPolicy: Retain on critical resources to prevent accidental deletion when removing CloudFormation stacks—it's your insurance policy against catastrophic data loss.