5.4 CloudFormation and Infrastructure as Code
Key Takeaways
- CloudFormation provisions AWS resources declaratively from JSON/YAML templates; Resources is the only mandatory template section.
- Stacks are the deployment unit; StackSets fan a stack out across many accounts and Regions from one operation.
- Change Sets preview exactly what will be added, modified, or deleted before you execute an update to a live stack.
- Drift detection finds resources changed manually outside CloudFormation; failed creates/updates roll back automatically by default.
- AWS CDK lets you write infrastructure in TypeScript/Python/Java and synthesizes CloudFormation; AWS SAM is a CloudFormation extension for serverless apps.
Quick Answer: CloudFormation is AWS's declarative infrastructure-as-code engine using YAML/JSON templates. A stack is the unit of deployment; StackSets roll a stack out across many accounts and Regions; Change Sets preview changes before you apply them; drift detection flags manual out-of-band edits. CDK lets you author IaC in programming languages, and SAM is a CloudFormation extension tuned for serverless.
Template Anatomy
| Section | Required | Purpose |
|---|---|---|
| AWSTemplateFormatVersion | No | Only valid value: "2010-09-09" |
| Description | No | Free-text summary |
| Parameters | No | Inputs supplied at stack creation |
| Mappings | No | Static lookups (e.g., AMI ID per Region) |
| Conditions | No | Create resources conditionally |
| Resources | Yes | The AWS resources to provision — the only mandatory section |
| Outputs | No | Values to display or export cross-stack |
Intrinsic functions glue templates together: Ref returns a resource's id or a parameter value, Fn::GetAtt pulls an attribute (such as an ALB DNS name), Fn::Sub interpolates variables, and Fn::ImportValue consumes another stack's exported output.
Stacks, StackSets, Change Sets, and Drift
| Concept | What it solves |
|---|---|
| Stack | All resources in a template managed as one unit; delete the stack to delete them all |
| StackSet | Deploy one template to many accounts and Regions in a single operation |
| Change Set | Show exactly what will be added/modified/deleted before executing an update |
| Drift detection | Report resources changed manually outside CloudFormation |
| Nested stacks | Factor reusable components into child templates |
| Cross-stack reference | Export an output from one stack, import it in another |
By default a failed create or update rolls back automatically to the last known-good state, preventing half-built infrastructure. A Change Set is the safe way to touch production: it surfaces destructive replacements (some property changes force resource re-creation) before you commit.
CloudFormation vs. CDK vs. Terraform, and SAM
| CloudFormation | AWS CDK | Terraform | |
|---|---|---|---|
| Language | YAML/JSON | TypeScript, Python, Java, C#, Go | HCL |
| Scope | AWS only | Synthesizes to CloudFormation | Multi-cloud |
| State | Managed by AWS | Via CloudFormation | External state file |
| Drift | Built-in | Inherits CFN drift | terraform refresh |
AWS SAM (Serverless Application Model) is a thin CloudFormation extension: shorthand for Lambda, API Gateway, DynamoDB, and Step Functions, plus the SAM CLI for local invoke and debug. SAM templates transform into ordinary CloudFormation at deploy time.
On the Exam: "Deploy identical infrastructure to 15 accounts across 3 Regions" → StackSets. "Preview changes before updating production" → Change Set. "Detect manual changes to managed resources" → drift detection. "Author infrastructure in Python" → CDK. "Simplify a serverless deployment" → SAM.
Deletion Protection, Retention, and Stack Policies
Production CloudFormation usage hinges on a few safety controls the exam likes to probe:
- DeletionPolicy on a resource controls what happens when the resource is removed or the stack is deleted.
Retainkeeps the resource (common for data stores),Snapshottakes a final snapshot (valid for RDS, EBS, ElastiCache, Redshift), andDelete(the default for most resources) removes it. An S3 bucket or RDS instance you must not lose should carryDeletionPolicy: Retain. - Termination protection on the stack blocks accidental
DeleteStackcalls until it is disabled. - Stack policies are JSON documents that protect specific resources from updates, preventing, for example, an accidental replacement of a production database during an unrelated update.
Reuse, Modularity, and Multi-Account Patterns
Large environments avoid one monolithic template. Nested stacks factor reusable pieces (a standard VPC, a logging stack) into child templates referenced by a parent. Cross-stack references export an output (Export) from one stack and Fn::ImportValue it elsewhere — useful for sharing a VPC ID across many application stacks. For organization-wide rollout, StackSets integrate with AWS Organizations so a new account automatically receives baseline stacks (guardrails, IAM roles, logging).
Common Traps
| Scenario | Wrong instinct | Correct answer |
|---|---|---|
| Same template, many accounts/Regions | Loop a script | StackSets |
| See changes before applying | Just update and watch | Change Set |
| Find out-of-band manual edits | Change Set | Drift detection |
| Preserve a database on stack delete | Hope it survives | DeletionPolicy: Retain/Snapshot |
| Author IaC in TypeScript | Hand-write YAML | AWS CDK (synthesizes CFN) |
Knowing that CDK and SAM both compile down to CloudFormation is the key conceptual takeaway: they change the authoring experience, not the underlying provisioning and state-management engine, which remains CloudFormation across all of them.
Parameters, Pseudo-Parameters, and Reuse Mechanics
Templates become reusable through Parameters (typed inputs like String, Number, or AWS-specific types such as AWS::EC2::KeyPair::KeyName that the console validates against your account) and Mappings (static lookups, classically an AMI ID per Region). Pseudo-parameters such as AWS::Region, AWS::AccountId, and AWS::StackName are supplied automatically and let one template adapt across Regions and accounts without editing.
For sensitive inputs, mark a parameter NoEcho: true so its value is masked in the console and events, and reference values stored in AWS Systems Manager Parameter Store or Secrets Manager rather than hard-coding credentials. Conditions combined with Fn::If let a single template create a small footprint in dev and a full Multi-AZ footprint in prod from one parameter — a frequently tested way to keep environments consistent while varying scale.
Together these features mean one well-authored template can drive an entire fleet of stacks through StackSets, each parameterized per account and Region while sharing identical, version-controlled logic.
A platform team must deploy the same CloudFormation stack to 20 AWS accounts across 4 Regions from a single operation. What should they use?
Before updating a live production stack, an engineer wants to see exactly which resources will be added, modified, or replaced. Which capability provides this?
After a manual console edit to a security group managed by CloudFormation, an auditor needs to know the live configuration no longer matches the template. Which feature surfaces this?