Skip to Content
Asterrr's Handbook
2 · New solutions

AWS CloudFormation

Template anatomy, intrinsic functions, stacks, nested stacks and StackSets, change sets, rollback behavior, helper scripts and safety controls.

Exam tasks: 2.1 (deployment strategies and IaC), 3.1, 1.4 (multi-account deployment)

The decision: how do you describe infrastructure so it deploys repeatably, updates safely, and rolls out to many accounts and Regions?

CloudFormation turns a template into a stack of resources and tracks them as a unit. You change infrastructure by changing the template, previewing with a change set, and updating the stack.

AWS OrganizationAdmin accountTarget accounts and RegionspreviewexecutedeployTemplateChange setStackStackSetStack instances
A template in S3 becomes a stack. Change sets preview updates, and StackSets repeat the template across accounts.
Resources
The only required template section
500
Resources per template. Use nested stacks to go beyond it
51,200 B / 1 MB
Largest template passed directly, and from S3
5
Alarms in a rollback configuration
180 min
Longest monitoring window for rollback triggers

Template anatomy

SectionPurpose
ParametersValues supplied at deploy time, including SSM parameter types such as the latest AMI ID
MappingsStatic lookup tables, for example an AMI per Region, read with Fn::FindInMap
ConditionsCreate a resource only when true, such as production only
ResourcesThe AWS resources. Required
OutputsValues to show or export for other stacks
TransformMacros, including AWS SAM (AWS::Serverless) and AWS::Include
  • Common intrinsic functions: Ref, Fn::GetAtt, Fn::Sub, Fn::Join, Fn::If, Fn::Select, Fn::ImportValue and Fn::GetAZs. Pseudo parameters include AWS::Region, AWS::AccountId and AWS::StackName.
  • Dynamic references read Systems Manager parameters and Secrets Manager secrets at deploy time, so secrets are not stored in the template.
  • The AWS CDK and SAM generate CloudFormation templates, so they inherit its behavior and limits.

Sharing across stacks

ApproachHow it worksWatch out for
Exports and Fn::ImportValueOne stack exports an output and others import itYou cannot delete or change an export while another stack imports it. Names are unique per Region
Nested stacksA parent stack creates child stacks from templates in S3Update through the parent. Good for reuse and for the resource limit
StackSetsOne template deployed to many accounts and RegionsSee below

StackSets

  • An administrator account defines the StackSet, and stack instances run in target accounts and Regions.
  • Service-managed permissions use AWS Organizations: roles are created for you, targets are OUs, and automatic deployment adds the stack to accounts that join the OU later. A delegated administrator can run it so the management account does not have to.
  • Self-managed permissions need an administration role in one account and an execution role in each target.
  • Operation preferences set maximum concurrent accounts and a failure tolerance, so a bad template stops early.

How updates and failures behave

  • Each property update is no interruption, some interruption or replacement. Replacement creates a new resource and deletes the old one, so a changed physical ID can break dependencies. Check the change set for Replacement.
  • A failed create rolls back by default and leaves a ROLLBACK_COMPLETE stack that you must delete. Disable rollback to keep the failed resources for troubleshooting.
  • A failed update returns to the previous state. If the rollback also fails, the stack is UPDATE_ROLLBACK_FAILED, and you fix the cause or continue update rollback, optionally skipping the resources that block it.
  • A service role lets the stack act with its own permissions, so deployers need only permission to pass that role.

Instance bootstrapping

  • cfn-init reads AWS::CloudFormation::Init metadata to install packages, write files and start services, which is declarative and re-runnable. User data only runs once at launch.
  • cfn-signal reports success or failure to a CreationPolicy (or a wait condition), so the stack waits until the application is ready instead of marking the instance created when it launches.
  • cfn-hup re-runs cfn-init when metadata changes.

Safety controls

ControlWhat it doesUse it when
Change setsPreview exactly what an update adds, modifies or replaces before running itAny production update. Look for Replacement: True
Stack policyJSON policy that denies update actions (for example Update:Replace or Update:Delete) on named resourcesProtecting a database from accidental replacement. Can be overridden for one update
Termination protectionBlocks stack deletionLong-lived stacks
DeletionPolicyRetain, Snapshot or Delete when a resource leaves the stack. RetainExceptOnCreate keeps it unless the create failedKeeping data after a stack is deleted
UpdateReplacePolicyThe same choices, applied to the old resource when an update replaces itSnapshotting a DB before a replacement
Drift detectionCompares live resources with the template and reports changes made outside CloudFormationFinding console hotfixes. It reports, it doesn't fix
Custom resourcesA Lambda function or SNS topic runs your code on create, update and delete, then signals success or failureAnything CloudFormation can't model, such as seeding data or calling a third-party API

Drift detection doesn't remediate

Drift detection only shows the difference. To undo drift you update the stack (or import resources), or you use AWS Config rules with remediation. An answer that says drift detection "automatically reverts changes" is wrong.

Custom resources that never respond

A custom resource Lambda function must send a response to the pre-signed URL CloudFormation gives it, including on delete and on errors. If it doesn't, the stack hangs until the operation times out.

For rolling the same template into many accounts and Regions, use StackSets with service-managed permissions through AWS Organizations. See multi-account governance.

Scenarios

Scenario · choose 2
A production stack contains an RDS instance. A template change modifies a property that CloudFormation implements by replacement. The team wants to see this before it happens and make sure the database can never be replaced by accident. Which TWO actions do this? Choose TWO.
Scenario
A security team needs the same IAM roles and a CloudTrail configuration in every current and future account of an organization, across three Regions, deployed from one place. Which approach fits?
Scenario
A stack launches an EC2 instance whose application takes about eight minutes to install. The stack reports CREATE_COMPLETE after two minutes, and a dependent stack fails because the application is not ready. How should the team fix it?

Further reading

On this page