Explain it simply
CloudFormation, simply
Think of a CloudFormation template as a blueprint and a stack as the house actually built from it. Every time you edit the blueprint and run an update, CloudFormation changes the house to match.
The catch is that some edits are as harmless as repainting a wall, while others secretly mean 'demolish this room and rebuild it' — furniture (your data) included. This lesson teaches you to preview what will change before work starts (change sets), find out when someone altered the house by hand (drift), undo a failed job (rollback), and forbid demolition of the rooms that matter (DeletionPolicy and stack policies).
Problem → Why → Solution
The 'just a rename' update
In AWS Fundamentals you created and deleted a CloudFormation stack. In production the dangerous operation is not create — it is update. Imagine a developer renames a DynamoDB table from orders-prod to orders-v2-prod 'for tidiness' and runs update-stack directly.
TableName is a replacement property. CloudFormation creates a new, empty table, repoints every reference to it, and then, in the cleanup phase, deletes the old table along with all of its data. No error is shown: the stack reaches UPDATE_COMPLETE and every order record is gone.
# Friday 17:55 - "just a small rename", pushed straight to production
aws cloudformation update-stack --stack-name orders-data-prod \
--template-body file://orders-data.yaml \
--parameters ParameterKey=EnvName,ParameterValue=prod
# TableName changed from orders-prod to orders-v2-prod. That property needs
# replacement: CloudFormation creates a NEW empty table, switches references,
# then DELETES the old table and every item in it.Why this happens
update-stack applies changes without showing them first, and nothing in the template protects the data. Every resource property has an 'update requires' type (no interruption, some interruption, or replacement), and replacement means a brand-new resource plus deletion of the old one. A change set would have shown this up front, and UpdateReplacePolicy: Retain would have kept the old table instead of deleting it.
Template anatomy and the stack lifecycle
The only required section of a template is Resources; everything else exists to make one template reusable across environments. A template can hold up to 500 resources, but you should split it long before it gets that big. The glue between sections is intrinsic functions such as !Ref, !GetAtt, !Sub and !If, plus pseudo parameters such as AWS::StackName and AWS::AccountId.
| Section | What it is for |
|---|---|
| Parameters | Inputs supplied at deploy time (EnvName, AWS::EC2::VPC::Id, SSM parameter types) |
| Mappings | Lookup tables keyed by a value (per-env sizes, retention periods) |
| Conditions | Turn resources or properties on and off from parameters (IsProd) |
| Resources | The AWS resources to create — the only mandatory section |
| Outputs | Values the stack publishes; with an Export, other stacks can use !ImportValue |
An export name must be unique within an account and region. While any other stack imports it, the export cannot be changed or deleted, which turns it into a strict contract between two stacks. !ImportValue also cannot cross regions.
On an update, CloudFormation compares the old and new templates and decides Add, Modify or Remove for each resource. Within Modify, each property's update behavior decides whether the change happens in place or by replacement. A change set is simply that plan, shown to you as a diff before anything is executed.
Every operation walks through a state machine. A successful create ends in CREATE_COMPLETE; a failed one (by default) ends in ROLLBACK_COMPLETE, a state from which the stack can only be deleted and recreated. A failed update rolls back to UPDATE_ROLLBACK_COMPLETE, and the stack keeps working in its previous shape. If the rollback itself fails, the stack is stuck in UPDATE_ROLLBACK_FAILED.
STACK STATES YOU WILL MEET
--------------------------
create-stack
|
v
CREATE_IN_PROGRESS --ok--> CREATE_COMPLETE <------------------+
| fail | |
v | update / execute-change-set |
ROLLBACK_IN_PROGRESS v |
| UPDATE_IN_PROGRESS --ok--> UPDATE_COMPLETE
v | fail
ROLLBACK_COMPLETE v
(delete and recreate) UPDATE_ROLLBACK_IN_PROGRESS
| \
v \ rollback fails
UPDATE_ROLLBACK_COMPLETE v
(old state, usable) UPDATE_ROLLBACK_FAILED
(fix, continue-update-rollback)- Edit the template in Git
- Create a change set
- Read Action and Replacement
- Execute, watch the events
- Detect drift on a schedule
Whenever you see Replacement: True on a stateful resource (database, table, bucket), stop and think again.
All the sections in one place
AWSTemplateFormatVersion: "2010-09-09"
Description: Minimal template showing every common section
Parameters: # inputs at deploy time
EnvName:
Type: String
AllowedValues: [dev, prod]
Default: dev
Mappings: # static lookup tables
EnvConfig:
dev:
RetentionSeconds: 345600
prod:
RetentionSeconds: 1209600
Conditions: # booleans derived from parameters
IsProd: !Equals [!Ref EnvName, prod]
Resources: # the only required section
WorkQueue:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: !FindInMap [EnvConfig, !Ref EnvName, RetentionSeconds]
SqsManagedSseEnabled: !If [IsProd, true, false]
Outputs: # values other stacks or people can read
WorkQueueUrl:
Value: !Ref WorkQueue
Export:
Name: !Sub "${AWS::StackName}-WorkQueueUrl"Parameters are inputs, Mappings are lookup tables, Conditions are booleans, Resources are what gets built, and Outputs are what gets published. !FindInMap looks up a per-environment value and !If picks a value based on a condition.
An orders-data stack that protects its data
This template builds an orders table, an order queue and a dead-letter queue. One template serves both dev and prod; only prod turns on point-in-time recovery and deletion protection. The table sets both DeletionPolicy and UpdateReplacePolicy to Retain, so neither deleting the stack nor a replacement can destroy the data.
AWSTemplateFormatVersion: "2010-09-09"
Description: Orders data layer - DynamoDB table plus work queue with a DLQ
Parameters:
EnvName:
Type: String
AllowedValues: [dev, prod]
Description: Deployment environment
Mappings:
EnvConfig:
dev:
MaxReceiveCount: 3
RetentionSeconds: 345600
prod:
MaxReceiveCount: 5
RetentionSeconds: 1209600
Conditions:
IsProd: !Equals [!Ref EnvName, prod]
Resources:
OrdersTable:
Type: AWS::DynamoDB::Table
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
PointInTimeRecoverySpecification:
PointInTimeRecoveryEnabled: !If [IsProd, true, false]
DeletionProtectionEnabled: !If [IsProd, true, false]
Tags:
- Key: env
Value: !Ref EnvName
OrdersDLQ:
Type: AWS::SQS::Queue
Properties:
MessageRetentionPeriod: 1209600
SqsManagedSseEnabled: true
OrdersQueue:
Type: AWS::SQS::Queue
Properties:
SqsManagedSseEnabled: true
MessageRetentionPeriod: !FindInMap [EnvConfig, !Ref EnvName, RetentionSeconds]
RedrivePolicy:
deadLetterTargetArn: !GetAtt OrdersDLQ.Arn
maxReceiveCount: !FindInMap [EnvConfig, !Ref EnvName, MaxReceiveCount]
Outputs:
TableName:
Value: !Ref OrdersTable
Export:
Name: !Sub "${AWS::StackName}-TableName"
QueueUrl:
Value: !Ref OrdersQueue
Export:
Name: !Sub "${AWS::StackName}-QueueUrl"
QueueName:
Value: !GetAtt OrdersQueue.QueueName
Export:
Name: !Sub "${AWS::StackName}-QueueName"Code breakdown
- Parameters / AllowedValues
AllowedValues: [dev, prod]Rejects typos such as prd or production before deployment begins. There is deliberately no Default, so nobody deploys prod by accident: EnvName must always be supplied.
- Mappings + !FindInMap
!FindInMap [EnvConfig, !Ref EnvName, RetentionSeconds]Per-environment values live in one table instead of many parameters. Messages are kept for 14 days in prod and 4 days in dev.
- Conditions + !If
PointInTimeRecoveryEnabled: !If [IsProd, true, false]Point-in-time recovery and deletion protection are enabled only in prod. You can also attach a condition to a whole resource (Condition: IsProd) to create it only in some environments.
- DeletionPolicy / UpdateReplacePolicy
DeletionPolicy: Retain UpdateReplacePolicy: RetainDeletionPolicy applies when the stack is deleted or the resource is removed from the template. UpdateReplacePolicy applies when a replacement update would delete the old resource. The second one is what prevents the data loss from the problem section.
- Outputs / Export
Name: !Sub "${AWS::StackName}-QueueName"Putting the stack name into the export name means orders-data-dev and orders-data-prod never collide in one account. Another stack can consume it with !ImportValue orders-data-prod-QueueName.
Sample output:
$ aws cloudformation deploy --template-file orders-data.yaml \
--stack-name orders-data-dev --parameter-overrides EnvName=dev
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - orders-data-dev
$ aws cloudformation list-exports --query "Exports[].Name" --output text
orders-data-dev-QueueName orders-data-dev-QueueUrl orders-data-dev-TableNameChange sets: read the diff before you execute
aws cloudformation deploy builds a change set behind the scenes and executes it immediately. In production, split that into two steps: create the change set, have a person or the pipeline read it, and only then execute it. If you prefer deploy, the --no-execute-changeset flag makes it stop after creating the change set.
The most important column to read is Replacement: True (it will definitely be rebuilt), Conditional (it may be, depending on another value) or False (in place).
STACK=orders-data-prod
aws cloudformation create-change-set --stack-name "$STACK" \
--change-set-name rename-table-2026-11-08 \
--template-body file://orders-data.yaml \
--parameters ParameterKey=EnvName,ParameterValue=prod
aws cloudformation wait change-set-create-complete --stack-name "$STACK" \
--change-set-name rename-table-2026-11-08
# Read the plan: which resources change, and are any replaced?
aws cloudformation describe-change-set --stack-name "$STACK" \
--change-set-name rename-table-2026-11-08 \
--query "Changes[].ResourceChange.{Action:Action,Id:LogicalResourceId,\
Replace:Replacement}" --output table
# Only after a human (or a policy check) approves:
aws cloudformation execute-change-set --stack-name "$STACK" \
--change-set-name rename-table-2026-11-08Block replacements automatically in a pipeline
A common pattern is to check describe-change-set output with jq and fail the pipeline if any stateful resource (AWS::DynamoDB::Table, AWS::RDS::DBInstance, AWS::S3::Bucket) shows Replacement True. People forget; scripts do not.
Drift detection: finding manual changes
During an incident someone adds a security group rule in the console or changes a queue's visibility timeout. When the real resource no longer matches the template, that is drift. On the next deploy CloudFormation writes the template value back, silently undoing the hotfix, or the update fails outright.
Drift detection compares the properties defined in the template with the live configuration and marks each resource IN_SYNC, MODIFIED, DELETED or NOT_CHECKED. It does not find brand-new resources that are not in the template, and not every resource type supports it.
DRIFT_ID=$(aws cloudformation detect-stack-drift --stack-name orders-data-prod \
--query StackDriftDetectionId --output text)
aws cloudformation describe-stack-drift-detection-status \
--stack-drift-detection-id "$DRIFT_ID" \
--query "{Status:DetectionStatus,Drift:StackDriftStatus}"
# Show only what changed, with the expected vs actual property values
aws cloudformation describe-stack-resource-drifts --stack-name orders-data-prod \
--stack-resource-drift-status-filters MODIFIED DELETED \
--query "StackResourceDrifts[].{Id:LogicalResourceId,Diff:PropertyDifferences}"When you find drift there are only two choices: if the change was right, put it in the template and redeploy; if it was wrong, redeploy the template to remove it. You can also check on a schedule with the AWS Config managed rule cloudformation-stack-drift-detection-check.
Rollbacks and stuck stacks
| State | What happened | What to do |
|---|---|---|
| ROLLBACK_COMPLETE | The first create failed and resources were removed | Read the first error event, delete the stack, create again |
| UPDATE_ROLLBACK_COMPLETE | Update failed, previous state restored | Stack still usable; fix the template and update again |
| UPDATE_ROLLBACK_FAILED | The rollback itself failed (e.g. a resource deleted by hand) | Fix the cause, then continue-update-rollback (with --resources-to-skip if needed) |
Always look for the earliest event with a FAILED status. The 'Resource creation cancelled' events after it are only consequences. In development, deploying with --disable-rollback keeps the failed resources around for inspection; you can then fix and update again, or roll back by hand with aws cloudformation rollback-stack. If you attach CloudWatch alarms as rollback triggers, CloudFormation also rolls an update back automatically when an alarm fires during it.
# Find the first failure (events are newest-first, so read from the bottom)
aws cloudformation describe-stack-events --stack-name orders-data-prod \
--query "StackEvents[?contains(ResourceStatus,'FAILED')].\
[Timestamp,LogicalResourceId,ResourceStatusReason]" --output text
# Stuck in UPDATE_ROLLBACK_FAILED because OrdersDLQ was deleted by hand:
aws cloudformation continue-update-rollback --stack-name orders-data-prod \
--resources-to-skip OrdersDLQProtecting data: DeletionPolicy, stack policies and termination protection
| Policy value | Meaning |
|---|---|
| Delete | Delete the resource (the default for most types) |
| Retain | Remove it from the stack but keep it in the account — delete it yourself later |
| Snapshot | Take a final snapshot before deleting (only snapshot-capable types such as RDS, EBS volumes, ElastiCache, Redshift) |
A stack policy is a JSON document that limits what stack updates may do. Once you set one, every resource is protected from updates by default, so you must add an explicit Allow. The example below allows all updates but forbids replacing or deleting OrdersTable. A stack policy cannot be removed, only replaced; for a genuinely necessary update you can override it temporarily with --stack-policy-during-update-body.
Termination protection guards the whole stack against delete-stack. Turn it on for every production stack.
cat > stack-policy.json <<'EOF'
{
"Statement": [
{ "Effect": "Allow", "Action": "Update:*", "Principal": "*", "Resource": "*" },
{
"Effect": "Deny",
"Action": ["Update:Replace", "Update:Delete"],
"Principal": "*",
"Resource": "LogicalResourceId/OrdersTable"
}
]
}
EOF
aws cloudformation set-stack-policy --stack-name orders-data-prod \
--stack-policy-body file://stack-policy.json
aws cloudformation update-termination-protection --enable-termination-protection \
--stack-name orders-data-prodNested stacks vs StackSets
These two have similar names but solve different problems. A nested stack (AWS::CloudFormation::Stack) breaks one big template into reusable pieces: a parent deploys its children and reads their outputs with !GetAtt Child.Outputs.Name. Everything stays in one account and one region and updates together. aws cloudformation package uploads the local child templates to S3 for you.
StackSets push one template to many accounts and many regions — for example a CloudTrail trail, Config rules or a baseline IAM role in every account. The SERVICE_MANAGED permission model works with AWS Organizations and deploys automatically when a new account joins an OU. Operation preferences control how many accounts are updated in parallel and how many failures stop the rollout.
AWSTemplateFormatVersion: "2010-09-09"
Description: Parent stack composing reusable child templates
Parameters:
EnvName:
Type: String
AllowedValues: [dev, prod]
Resources:
DataStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://cfn-tpl-111122223333.s3.amazonaws.com/orders-data.yaml
Parameters:
EnvName: !Ref EnvName
AlarmsStack:
Type: AWS::CloudFormation::Stack
Properties:
TemplateURL: https://cfn-tpl-111122223333.s3.amazonaws.com/alarms.yaml
Parameters:
QueueName: !GetAtt DataStack.Outputs.QueueName
Outputs:
OrdersTableName:
Value: !GetAtt DataStack.Outputs.TableName# One baseline template -> every account in an OU, two regions
aws cloudformation create-stack-set --stack-set-name org-baseline \
--template-body file://baseline.yaml \
--permission-model SERVICE_MANAGED \
--auto-deployment Enabled=true,RetainStacksOnAccountRemoval=false \
--capabilities CAPABILITY_NAMED_IAM
aws cloudformation create-stack-instances --stack-set-name org-baseline \
--deployment-targets OrganizationalUnitIds=ou-ab12-34cd56ef \
--regions us-east-1 ap-southeast-1 \
--operation-preferences MaxConcurrentPercentage=25,FailureTolerancePercentage=10| Nested stacks | StackSets | |
|---|---|---|
| Problem solved | Template too big, want reuse | Same thing in many accounts/regions |
| Scope | One account, one region | Many accounts x many regions |
| Passing data | Parameters + !GetAtt Outputs | Parameters (per-instance overrides) |
In production
How production teams run CloudFormation
On mature teams, not everyone can update a stack from the console. Templates live in Git, and every pull request runs cfn-lint (syntax and property checks) plus cfn-guard or Checkov (policy checks such as 'every bucket must be encrypted'). After merge, the pipeline creates a change set, checks it for replacements, collects a human approval for prod, and only then executes it.
Stacks are split by lifecycle: a network stack that changes maybe once a year, a data stack that rarely changes and retains everything, and application stacks deployed ten times a day. That way a bad app deploy cannot touch the database. At the organization level, StackSets or Control Tower customizations give every new account the same baseline, and drift detection runs weekly with results opened as tickets. Many teams also check automatically that termination protection is switched on for every production stack.
Common mistakes
Common mistakes
- Leaving UpdateReplacePolicy off stateful resources. DeletionPolicy: Retain alone does not protect against a replacement update. Set both on every table, bucket and database.
- Hard-coding physical names (TableName, BucketName) without need. Two resources with the same name cannot exist at once, so updates that need replacement fail, and deploying a second environment collides. Let CloudFormation generate names and publish them as Outputs.
- Using Exports everywhere. While a value is imported, the producer stack cannot change that output, so stacks become chained together. For values that change often, SSM Parameter Store is more flexible.
- Trying to update a stack in ROLLBACK_COMPLETE. A stack whose first create failed cannot be updated; delete it and create it again.
- Ignoring drift. A console hotfix gets silently reverted on the next deploy, or makes the update fail.
💰 Cost & Cleanup
CloudFormation itself is free for resources in the AWS:: namespaces (third-party resource types and hooks are charged per operation). What costs money is what the stack creates. The on-demand DynamoDB table and SQS queues in this lab cost close to nothing when idle and usually fall inside the free tier. The trap is the retained table: after you delete the stack it stays in your account and keeps accruing storage charges until you delete it yourself.
Clean up when you are done
TABLE=$(aws cloudformation describe-stacks --stack-name orders-data-dev \
--query "Stacks[0].Outputs[?OutputKey=='TableName'].OutputValue" --output text)
aws cloudformation delete-stack --stack-name orders-data-dev
aws cloudformation wait stack-delete-complete --stack-name orders-data-dev
# DeletionPolicy: Retain left the table behind on purpose - remove it by hand
aws dynamodb delete-table --table-name "$TABLE"Mini challenge
An alarm stack that imports an export
Write an orders-alarms.yaml template that imports the QueueName export from the orders-data stack and raises a CloudWatch alarm when messages sit in the queue for too long.
- Build the export name with !Sub from a DataStackName parameter (default orders-data-dev) and use !ImportValue
- Alarm on the ApproximateAgeOfOldestMessage metric
- Take the threshold from Mappings per environment (dev 3600 seconds, prod 300 seconds)
- Pass cfn-lint with no errors
Expected: Once the alarm stack is deployed, trying to delete orders-data-dev fails with an 'Export ... cannot be deleted as it is in use' error, which proves the export contract is working.
Show hint
You cannot nest the short-form !Sub directly inside !ImportValue, so write Fn::Sub in long form. The SQS metric namespace is AWS/SQS and its dimension is QueueName.
Show solution
AWSTemplateFormatVersion: "2010-09-09"
Description: Alarm on stuck messages in the orders queue
Parameters:
EnvName:
Type: String
AllowedValues: [dev, prod]
Default: dev
DataStackName:
Type: String
Default: orders-data-dev
Mappings:
AgeThreshold:
dev:
Seconds: 3600
prod:
Seconds: 300
Resources:
OldestMessageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmDescription: Orders are waiting too long in the queue
Namespace: AWS/SQS
MetricName: ApproximateAgeOfOldestMessage
Dimensions:
- Name: QueueName
Value: !ImportValue
Fn::Sub: "${DataStackName}-QueueName"
Statistic: Maximum
Period: 60
EvaluationPeriods: 5
Threshold: !FindInMap [AgeThreshold, !Ref EnvName, Seconds]
ComparisonOperator: GreaterThanThreshold
TreatMissingData: notBreaching
Outputs:
AlarmName:
Value: !Ref OldestMessageAlarmQuick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Only Resources is required; Parameters, Mappings, Conditions and Outputs make one template reusable across environments.
- Preview every production update with a change set and pay special attention to the Replacement column.
- Give every stateful resource both DeletionPolicy and UpdateReplacePolicy, and add stack policies and termination protection on top.
- Drift detection finds console changes; know how to get out of each rollback state.
- Nested stacks split templates; StackSets fan one template out across accounts and regions.
AWS CloudFormation User Guide — AWS Documentation
Update stacks using change sets — AWS Documentation
AWS CloudFormation StackSets — AWS Documentation