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.
Template anatomy
| Section | Purpose |
|---|---|
| Parameters | Values supplied at deploy time, including SSM parameter types such as the latest AMI ID |
| Mappings | Static lookup tables, for example an AMI per Region, read with Fn::FindInMap |
| Conditions | Create a resource only when true, such as production only |
| Resources | The AWS resources. Required |
| Outputs | Values to show or export for other stacks |
| Transform | Macros, including AWS SAM (AWS::Serverless) and AWS::Include |
- Common intrinsic functions:
Ref,Fn::GetAtt,Fn::Sub,Fn::Join,Fn::If,Fn::Select,Fn::ImportValueandFn::GetAZs. Pseudo parameters includeAWS::Region,AWS::AccountIdandAWS::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
| Approach | How it works | Watch out for |
|---|---|---|
Exports and Fn::ImportValue | One stack exports an output and others import it | You cannot delete or change an export while another stack imports it. Names are unique per Region |
| Nested stacks | A parent stack creates child stacks from templates in S3 | Update through the parent. Good for reuse and for the resource limit |
| StackSets | One template deployed to many accounts and Regions | See 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_COMPLETEstack 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-initreadsAWS::CloudFormation::Initmetadata to install packages, write files and start services, which is declarative and re-runnable. User data only runs once at launch.cfn-signalreports 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-hupre-runscfn-initwhen metadata changes.
Safety controls
| Control | What it does | Use it when |
|---|---|---|
| Change sets | Preview exactly what an update adds, modifies or replaces before running it | Any production update. Look for Replacement: True |
| Stack policy | JSON policy that denies update actions (for example Update:Replace or Update:Delete) on named resources | Protecting a database from accidental replacement. Can be overridden for one update |
| Termination protection | Blocks stack deletion | Long-lived stacks |
| DeletionPolicy | Retain, Snapshot or Delete when a resource leaves the stack. RetainExceptOnCreate keeps it unless the create failed | Keeping data after a stack is deleted |
| UpdateReplacePolicy | The same choices, applied to the old resource when an update replaces it | Snapshotting a DB before a replacement |
| Drift detection | Compares live resources with the template and reports changes made outside CloudFormation | Finding console hotfixes. It reports, it doesn't fix |
| Custom resources | A Lambda function or SNS topic runs your code on create, update and delete, then signals success or failure | Anything 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
A change set previews exactly what changes, including replacement, and a stack policy blocks the replace action on that resource. Drift detection compares live resources to the template and says nothing about a planned update. Termination protection blocks stack deletion, not resource replacement. A nested stack changes organization, not safety.
Service-managed StackSets use Organizations to create the roles and, with automatic deployment, add stack instances for new accounts. Scripts and tickets leave gaps. A nested stack deploys in one account. Exports and imports work only inside one account and Region.
A creation policy makes CloudFormation wait for success signals before marking the resource created. A bigger instance only shortens install time. DeletionPolicy affects deletion, and removing the dependent stack gives up the requirement.
Related
- Deployment strategies: CodeDeploy, blue/green and automated rollback.
- Multi-account governance: StackSets with Organizations and Control Tower.
- Configuration and patching: Systems Manager for in-place change.
Further reading
Deployment strategies
All-at-once, rolling, immutable, blue/green, canary and linear deployments, how CodeDeploy, Elastic Beanstalk and CloudFormation implement them, and how to roll back safely.
AWS Elastic Beanstalk
Environment tiers, platforms, deployment policies, configuration with ebextensions, health reporting and the database and blue/green pitfalls.