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.
Last updated: June 2026

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

SectionRequiredPurpose
AWSTemplateFormatVersionNoOnly valid value: "2010-09-09"
DescriptionNoFree-text summary
ParametersNoInputs supplied at stack creation
MappingsNoStatic lookups (e.g., AMI ID per Region)
ConditionsNoCreate resources conditionally
ResourcesYesThe AWS resources to provision — the only mandatory section
OutputsNoValues 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

ConceptWhat it solves
StackAll resources in a template managed as one unit; delete the stack to delete them all
StackSetDeploy one template to many accounts and Regions in a single operation
Change SetShow exactly what will be added/modified/deleted before executing an update
Drift detectionReport resources changed manually outside CloudFormation
Nested stacksFactor reusable components into child templates
Cross-stack referenceExport 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

CloudFormationAWS CDKTerraform
LanguageYAML/JSONTypeScript, Python, Java, C#, GoHCL
ScopeAWS onlySynthesizes to CloudFormationMulti-cloud
StateManaged by AWSVia CloudFormationExternal state file
DriftBuilt-inInherits CFN driftterraform 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. Retain keeps the resource (common for data stores), Snapshot takes a final snapshot (valid for RDS, EBS, ElastiCache, Redshift), and Delete (the default for most resources) removes it. An S3 bucket or RDS instance you must not lose should carry DeletionPolicy: Retain.
  • Termination protection on the stack blocks accidental DeleteStack calls 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

ScenarioWrong instinctCorrect answer
Same template, many accounts/RegionsLoop a scriptStackSets
See changes before applyingJust update and watchChange Set
Find out-of-band manual editsChange SetDrift detection
Preserve a database on stack deleteHope it survivesDeletionPolicy: Retain/Snapshot
Author IaC in TypeScriptHand-write YAMLAWS 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.

Test Your Knowledge

A platform team must deploy the same CloudFormation stack to 20 AWS accounts across 4 Regions from a single operation. What should they use?

A
B
C
D
Test Your Knowledge

Before updating a live production stack, an engineer wants to see exactly which resources will be added, modified, or replaced. Which capability provides this?

A
B
C
D
Test Your Knowledge

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?

A
B
C
D