SkillSprout
Chapter 3 · Lesson 1
Intermediate
6 min read

CloudFormation Operations: Stacks, Change Sets and Drift

Overview

AWS CloudFormation provisions infrastructure from declarative templates (YAML/JSON). A deployed template is a stack; CloudFormation works out the order of creation, calls the APIs for you, and rolls back if something fails. That makes environments repeatable, reviewable and version-controlled.

Think of a template as an architect's blueprint and a stack as the finished building. If someone later moves a wall without updating the blueprint, you have drift – and part of the SysOps job is detecting and reconciling that.

The exam focuses on operating stacks: understanding failed/rollback states, previewing updates with change sets, protecting data with DeletionPolicy, signalling readiness with CreationPolicy, and deploying across accounts with StackSets.

Key Concepts

  • Template sections: Parameters, Mappings, Conditions, Resources (required), Outputs; intrinsic functions such as Ref, GetAtt, Sub, FindInMap, ImportValue.
  • Change sets preview what an update will add, modify, replace or delete before you execute it.
  • Rollback: a failed create ends in ROLLBACK_COMPLETE (must be deleted); a failed update rolls back to the previous state (UPDATE_ROLLBACK_COMPLETE).
  • DeletionPolicy (Delete, Retain, Snapshot) and UpdateReplacePolicy protect data resources; stack termination protection prevents deletion.
  • Drift detection compares live resources to the template and reports MODIFIED/DELETED resources; it does not fix them.
  • CreationPolicy + cfn-signal make CloudFormation wait for an instance to finish bootstrapping; WaitCondition is the older equivalent.
  • StackSets deploy stacks to many accounts and Regions (service-managed with Organizations or self-managed).
  • Stack policies prevent accidental updates to critical resources; IAM service roles let CloudFormation act with scoped permissions.

Detailed Notes

A small production-style template

yaml
AWSTemplateFormatVersion: "2010-09-09"
Parameters:
  Env: { Type: String, AllowedValues: [dev, prod], Default: dev }
  LatestAmi:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
Conditions:
  IsProd: !Equals [!Ref Env, prod]
Resources:
  Db:
    Type: AWS::RDS::DBInstance
    DeletionPolicy: Snapshot
    UpdateReplacePolicy: Snapshot
    Properties:
      DBInstanceClass: db.t3.medium
      Engine: mysql
      AllocatedStorage: "20"
      MultiAZ: !If [IsProd, true, false]
      ManageMasterUserPassword: true
      MasterUsername: admin
  Web:
    Type: AWS::EC2::Instance
    CreationPolicy:
      ResourceSignal: { Count: 1, Timeout: PT10M }
    Properties:
      ImageId: !Ref LatestAmi
      InstanceType: t3.micro
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          dnf install -y httpd && systemctl enable --now httpd
          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource Web --region ${AWS::Region}
Outputs:
  WebId: { Value: !Ref Web, Export: { Name: !Sub "${AWS::StackName}-WebId" } }

Change sets workflow

bash
aws cloudformation create-change-set --stack-name app --change-set-name v2 \
  --template-body file://app.yaml --parameters ParameterKey=Env,ParameterValue=prod \
  --capabilities CAPABILITY_NAMED_IAM
aws cloudformation describe-change-set --stack-name app --change-set-name v2 \
  --query "Changes[].ResourceChange.[LogicalResourceId,Action,Replacement]"
aws cloudformation execute-change-set --stack-name app --change-set-name v2

Replacement: True means the physical resource will be recreated – data loss risk for databases.

Stack states you must recognise

StateMeaning / action
CREATE_FAILED -> ROLLBACK_COMPLETEDelete the stack and recreate after fixing
UPDATE_ROLLBACK_COMPLETEUpdate failed, old config restored
UPDATE_ROLLBACK_FAILEDUse ContinueUpdateRollback (skip resources if needed)
DELETE_FAILEDNon-empty S3 bucket, dependent resource, retained ENI; fix then retry
REVIEW_IN_PROGRESSChange set created for a new stack

Drift detection

bash
aws cloudformation detect-stack-drift --stack-name app
aws cloudformation describe-stack-resource-drifts --stack-name app \
  --stack-resource-drift-status-filters MODIFIED DELETED

Fix drift by reverting the manual change or updating the template to match, then updating the stack. You can also import existing resources into a stack.

Deletion and update protection

SettingEffect
DeletionPolicy: RetainResource kept when stack is deleted
DeletionPolicy: SnapshotFinal snapshot for EBS, RDS, ElastiCache, etc.
UpdateReplacePolicySame, but when update replaces the resource
Termination protectionBlocks DeleteStack
Stack policyDenies updates to named resources unless overridden

StackSets

bash
aws cloudformation create-stack-set --stack-set-name baseline --template-body file://baseline.yaml \
  --permission-model SERVICE_MANAGED --auto-deployment Enabled=true,RetainStacksOnAccountRemoval=false
aws cloudformation create-stack-instances --stack-set-name baseline \
  --deployment-targets OrganizationalUnitIds=ou-abcd-12345678 --regions us-east-1 eu-west-1

Troubleshooting

SymptomLikely cause
InsufficientCapabilitiesMissing CAPABILITY_IAM / CAPABILITY_NAMED_IAM / CAPABILITY_AUTO_EXPAND
Stack stuck in CREATE_IN_PROGRESS for an instancecfn-signal never sent: check /var/log/cfn-init.log, cloud-init-output.log, SG/outbound access
Export cannot be deletedAnother stack imports it (Fn::ImportValue)
Update fails on resource limitService quota exhausted
Resource already existsFixed names clash; avoid hard-coded names or use import

Use aws cloudformation describe-stack-events to find the first FAILED event – the root cause is there; later failures are usually consequences. Use --disable-rollback (or "preserve successfully provisioned resources") to debug a failed create.### Stack policies, rollback behaviour and cross-stack references

TopicWhat to know
Stack policyJSON that blocks updates to named resources (for example the production database) unless overridden
Rollback triggersCloudWatch alarms that roll back an update if they fire during monitoring time
UPDATE_ROLLBACK_FAILEDUse continue-update-rollback (optionally skipping resources) after fixing the cause
DeletionPolicyRetain, Snapshot, Delete protect data when a resource or stack is removed
UpdateReplacePolicySame protection when an update replaces a resource
Exports / ImportValueCross-stack references; an export in use cannot be changed or deleted
Nested stacksReusable child templates managed from a parent
Drift detectionReports resources changed outside CloudFormation
bash
aws cloudformation detect-stack-drift --stack-name prod-network
aws cloudformation describe-stack-resource-drifts --stack-name prod-network --stack-resource-drift-status-filters MODIFIED DELETED
aws cloudformation continue-update-rollback --stack-name prod-app --resources-to-skip LogicalId1
aws cloudformation deploy --template-file t.yaml --stack-name prod-app --capabilities CAPABILITY_NAMED_IAM

Templates that create IAM resources require an explicit capabilities acknowledgement. Use IaC generator / resource import to bring existing resources under management, and service roles so users do not need broad permissions themselves.

Real World Example

Scenario – safely changing a production database. A developer edits a template, changing the RDS DBInstanceIdentifier, a property that requires replacement. Before executing, the ops engineer creates a change set and sees Replacement: True for the database. They stop the change, revert the property, and add DeletionPolicy: Snapshot for safety.

Later, a quarterly drift detection run flags a security group modified by hand. The team removes the manual rule, adds the needed rule to the template, and enforces changes only through the pipeline plus an SCP blocking console modifications.

Architecture Diagram

Safe CloudFormation change workflow
Architecture
AWS Cloud
Template in Git
Change setpreview
Stackexecute update
Resources
Drift detection
  1. 1Templates are stored in version control and reviewed.
  2. 2A change set previews adds, modifications and replacements.
  3. 3After approval the change set is executed and CloudFormation updates resources in dependency order.
  4. 4Drift detection periodically verifies live resources still match the template.

Best Practices

  • ✓Always use change sets for production updates and review Replacement flags.
  • ✓Set DeletionPolicy/UpdateReplacePolicy (Snapshot/Retain) on stateful resources and enable termination protection.
  • ✓Use parameters, SSM parameter types and mappings rather than hard-coded IDs and names.
  • ✓Run drift detection on a schedule and prevent console edits with IAM/SCPs.
  • ✓Use StackSets (service-managed) for baselines across accounts and Regions.

Common Interview Questions

Exam Tips

SOA-C03 focus

  • Preview changes -> change set. Detect manual changes -> drift detection.
  • Keep data when a stack is deleted -> DeletionPolicy Retain/Snapshot.
  • Deploy to many accounts/Regions -> StackSets.
  • Stack waiting on bootstrap -> CreationPolicy + cfn-signal; IAM resources need CAPABILITY_IAM.

Finished this lesson?

0 of 46 lessons done · 0% of the course