SkillSprout
Chapter 3 · Lesson 1
Advanced
7 min read

CloudFormation Advanced: Nested Stacks, Change Sets, Drift and Custom Resources

Overview

AWS CloudFormation turns infrastructure into declarative templates. You describe the desired end state, CloudFormation works out the order of operations, creates or updates resources, and rolls back if something fails. A running set of resources created from one template is a stack.

Imagine an architect's blueprint combined with a construction crew that can also renovate: you edit the blueprint, the crew compares it with the building, shows you a plan (change set), and carries out only the differences. If a wall collapses midway the crew restores the previous state.

The professional exam expects fine-grained knowledge: update behaviours (no interruption, some interruption, replacement), DeletionPolicy, CreationPolicy and cfn-signal, rollback triggers, nested stacks, drift detection, custom resources with Lambda, and cross-stack references.

Key Concepts

  • Change sets preview what an update will add, modify, replace or remove before you execute it.
  • Update behaviours: No interruption, Some interruption, Replacement (new physical ID); the resource reference table in docs says which applies per property.
  • DeletionPolicy: Delete, Retain, Snapshot (and RetainExceptOnCreate); UpdateReplacePolicy controls what happens to the old resource on replacement.
  • CreationPolicy with cfn-signal makes CloudFormation wait for instances/ASG to signal success; UpdatePolicy governs rolling updates of an ASG.
  • Nested stacks (AWS::CloudFormation::Stack) reuse templates; cross-stack references use Export and Fn::ImportValue.
  • Drift detection reports resources whose actual configuration differs from the template; it does not fix them.
  • Custom resources (Lambda-backed or SNS-backed) let a stack call arbitrary logic and must send a response to a pre-signed S3 URL.
  • Rollback triggers monitor CloudWatch alarms during create/update and roll the stack back if an alarm fires; stack policies protect resources from updates.

Detailed Notes

Template anatomy refresher

SectionPurpose
ParametersInputs, including SSM parameter types (AWS::SSM::Parameter::Value<String>)
Mappings / ConditionsStatic lookups and conditional resources
ResourcesThe only required section
OutputsValues to display or Export
TransformMacros such as AWS::Serverless-2016-10-31 or AWS::Include
RulesValidate parameter combinations

Change sets

bash
aws cloudformation create-change-set --stack-name orders \
  --change-set-name add-cache --template-body file://template.yaml \
  --capabilities CAPABILITY_IAM --change-set-type UPDATE
aws cloudformation describe-change-set --stack-name orders --change-set-name add-cache
aws cloudformation execute-change-set --stack-name orders --change-set-name add-cache

Review the Replacement column; replacing a database or an EBS volume may lose data. Pipelines commonly use CHANGE_SET_REPLACE followed by a manual approval and CHANGE_SET_EXECUTE.

Protecting data

yaml
Database:
  Type: AWS::RDS::DBInstance
  DeletionPolicy: Snapshot
  UpdateReplacePolicy: Snapshot
  Properties:
    Engine: postgres
    ManageMasterUserPassword: true
    MasterUsername: app
    AllocatedStorage: 50
    DBInstanceClass: db.m6g.large

Stack policies deny updates to critical resources unless explicitly overridden; termination protection blocks stack deletion.

Waiting for instances: CreationPolicy and signals

yaml
WebASG:
  Type: AWS::AutoScaling::AutoScalingGroup
  CreationPolicy:
    ResourceSignal: { Count: 2, Timeout: PT10M }
  UpdatePolicy:
    AutoScalingRollingUpdate:
      MinInstancesInService: 2
      MaxBatchSize: 1
      PauseTime: PT5M
      WaitOnResourceSignals: true
  Properties:
    # ...

Instances run cfn-init (reads AWS::CloudFormation::Init metadata) and then cfn-signal -e $? --stack ${AWS::StackName} --resource WebASG --region ${AWS::Region}. In a template, shell variables that look like ${Name} are substituted by Fn::Sub, so literal shell variables need ${!Name}. Other helpers: cfn-hup re-applies metadata on changes, and WaitCondition is the legacy alternative.

Nested stacks vs cross-stack references

FeatureNested stacksExport / ImportValue
RelationshipParent owns children; updated and deleted togetherIndependent stacks with a dependency
ReuseModule reuse within a parentShare long-lived outputs (VPC ID)
ConstraintTemplate URL must be in S3An export cannot be modified/deleted while imported; names unique per Region

Use nested stacks for composition (a standard VPC module) and cross-stack references for loosely coupled layers. Modern alternatives: CloudFormation modules, registry resource types and language-level reuse via CDK.

Drift detection

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

Drift detection reports MODIFIED, DELETED or IN_SYNC. Combine with AWS Config managed rule cloudformation-stack-drift-detection-check for continuous checks, then remediate by re-deploying the template (or importing changes). Resource import brings existing resources under stack management using a change set of type IMPORT.

Custom resources

yaml
LookupAmi:
  Type: Custom::AmiLookup
  Properties:
    ServiceToken: !GetAtt AmiLookupFunction.Arn
    Region: !Ref AWS::Region

The Lambda receives RequestType (Create/Update/Delete), ResponseURL and StackId, and must PUT a JSON response with Status SUCCESS or FAILED. A function that never responds hangs the stack until the one-hour timeout, a classic exam trap, particularly on Delete. Use the cfn-response module or the crhelper library, and always handle Delete.

Rollback behaviour

  • Create failure: rolls back (deletes created resources) unless --on-failure DO_NOTHING|ROLLBACK is changed or DisableRollback set for debugging.
  • Update failure: reverts to the last known good state, ending in UPDATE_ROLLBACK_COMPLETE.
  • UPDATE_ROLLBACK_FAILED: use ContinueUpdateRollback, skipping resources that cannot roll back.
  • Rollback triggers (up to 5 alarms) with a monitoring period up to 180 minutes.

Other useful features

Dynamic references ({{resolve:ssm:/app/db/host}}, {{resolve:secretsmanager:...}}) pull values at deploy time without exposing them in the template; Fn::Sub, Fn::GetAtt, Fn::FindInMap; Conditions; and CloudFormation Guard or cfn-lint to validate templates in a pipeline. Hooks (for example the Lambda hook) can block non-compliant resources before provisioning.

Change management workflow for IaC

A reliable change process treats templates like application code. Store them in Git, require pull request review, and run cfn-lint, cfn-guard and unit tests (for CDK, assertion tests) in CI. A pipeline then creates a change set and shows the diff for approval before execution.

Update behaviourMeaningExample property
No interruptionResource updated in place with no disruptionTags, IAM policy documents
Some interruptionBrief outage but physical ID keptEC2 instance type (stop/start)
ReplacementNew resource created, old deletedRDS DBInstanceIdentifier, Lambda function name

Use aws cloudformation create-change-set --change-set-type UPDATE and inspect the Replacement field, which can be True, False or Conditional. Protect stateful resources with DeletionPolicy and UpdateReplacePolicy, keep a stack policy on critical stacks and use rollback triggers (CloudWatch alarms monitored during and after the update) to revert automatically. Resource import adopts existing resources into a stack, and drift detection reports out-of-band changes; remediate by updating the template or reverting the resource, never by ignoring drift.

Real World Example

Scenario: a retailer standardises its platform. A shared nested VPC template feeds every application stack. Each application pipeline creates a change set, runs cfn-guard policy checks, and waits for approval before executing it.

The ASG uses CreationPolicy and an UpdatePolicy rolling update with cfn-signal, so a bad AMI never replaces healthy instances. Databases use DeletionPolicy and UpdateReplacePolicy Snapshot, and a nightly Config rule runs drift detection and opens a ticket when someone edits a security group by hand.

Architecture Diagram

Safe CloudFormation update workflow
Architecture
AWS Cloud
TemplateGit + cfn-guard
Change setpreview
Region
Stack updaterollback triggers
Alarms
Drift checkConfig rule

Preview, approve, execute with alarms watching, and detect drift afterwards.

  1. 1The template is validated with cfn-lint and cfn-guard in CI.
  2. 2A change set shows adds, modifies and replacements.
  3. 3A reviewer approves and the change set executes.
  4. 4Rollback triggers and signals revert the stack if health degrades.
  5. 5Continuous drift detection flags out-of-band changes afterwards.

Best Practices

  • ✓Always review a change set for Replacement before touching stateful resources.
  • ✓Set DeletionPolicy and UpdateReplacePolicy to Snapshot or Retain on data stores.
  • ✓Use CreationPolicy/UpdatePolicy with cfn-signal for Auto Scaling groups.
  • ✓Handle Delete requests and timeouts in every custom resource Lambda.
  • ✓Use dynamic references for secrets and run drift detection on a schedule.

Common Interview Questions

Exam Tips

DOP-C02 focus

  • "Preview changes before applying" = change set; "detect manual changes" = drift detection.
  • "Wait until instance is ready" = CreationPolicy + cfn-signal.
  • Stateful resource replaced by an update = UpdateReplacePolicy Snapshot protects data.
  • Custom resource stuck = missing response, especially on Delete.

Finished this lesson?

0 of 44 lessons done · 0% of the course