Ravindra BagaleCourses & study guides मराठी Track your progress

AWS CloudFormation Deep Dive: Infrastructure as Code for Beginners

Terraform and CDK are popular, but many enterprises still ship AWS CloudFormation YAML/JSON every day. CloudFormation is the native IaC engine: you declare resources, AWS creates a stack, and change sets show what will break before you update production.

What you'll learn in this chapter

  • Why native IaC still matters
  • Templates, stacks, change sets, drift
  • Parameters, mappings, outputs, nested stacks
  • CFN vs CDK vs Terraform decision
  • Lab, errors, FAQ, interview

1. Everyday example first

A Mumbai bank must create identical VPCs in three accounts. Clicking the console thrice guarantees drift. One CloudFormation template + StackSets (or three stacks) keeps CIDRs, tags and flow logs aligned — and auditors see the template in Git.

2. Why CloudFormation deep?

Why do we need this?

Beginners learn create stack. Pros learn change sets, drift detection, nested stacks, custom resources and rollback triggers. Interviews and brownfield jobs still ask CFN even if your team prefers CDK.

3. What are the core pieces?

What is it?

PieceMeaning
TemplateYAML/JSON of resources
StackLive set of resources from a template
Change setPreview of an update before apply
DriftConsole/API changed resource away from template
Nested stackStack that owns child stacks
Template → Change set → Update → MonitorWant safe infra change
Preview then apply

4. How to work safely

How to do it (step by step)

  1. Keep templates in Git; never edit only in console.
  2. Always create a change set for prod updates.
  3. Use Parameters for env names; Mappings for region AMI tables.
  4. Export Outputs for cross-stack refs or use nested stacks.
  5. Turn on termination protection for prod stacks.
  6. Run drift detection weekly on critical stacks.
AWSTemplateFormatVersion: '2010-09-09'
Description: Tiny S3 lab bucket
Parameters:
  ProjectName:
    Type: String
    Default: cfn-lab
Resources:
  LabBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
Outputs:
  BucketName:
    Value: !Ref LabBucket

5. CFN vs CDK vs Terraform

ToolPick when
CloudFormationNative, StackSets, org standard YAML
CDKWant TypeScript/Python generate CFN
TerraformMulti-cloud or existing TF estate

6. Industries

  • Banks: approved CFN modules in a private registry
  • SaaS: nested stacks per tenant baseline
  • Gov projects: CFN + CodePipeline gates
  • Startups: start CFN, grow into CDK

7. Lab: deploy a tiny encrypted bucket stack

Do this in ap-south-1 (Mumbai) unless your org forbids it. Set a budget alert first.

How to do it (step by step)

  1. Save the template above as lab.yaml.
  2. Console → CloudFormation → Create stack with new resources.
  3. Region ap-south-1; parameter ProjectName=yourname-lab.
  4. After CREATE_COMPLETE, note Outputs BucketName.
  5. Create a change set that adds a bucket tag Owner=you.

Cleanup (stop billing)

  1. Delete the stack after verifying DeletionPolicy.
  2. Confirm no leftover buckets with your prefix.

8. Common errors and fixes

Each row is a real mistake students and juniors hit. Read the fix before you panic.

Error / symptomFix
Updated prod without change setAlways change set + peer review.
Circular dependency between resourcesSplit stacks or use DependsOn carefully.
Hard-coded account idUse Pseudo parameters AWS::AccountId.
Stack stuck DELETE_FAILEDEmpty S3/ENIs; check Retention.
Drift ignored for monthsWeekly drift + reopen tickets.
Nested stack parameters explosionPass maps carefully; document contracts.
IAM star in template for speedScope actions and resources.
No rollback triggers on ALMAdd CloudWatch alarm rollback triggers.
Edited resource in consoleRe-import or reconcile template.
Wrong YAML indentUse cfn-lint before deploy.

9. Troubleshooting checklist

  1. CREATE_FAILED → Events tab first line.
  2. cfn-lint locally before upload.
  3. Check service quotas (EIP, VPC).
  4. Permissions: cloudformation + iam PassRole.
  5. Change set empty? Template identical.
  6. Export name already exists — unique exports.

10. FAQ

Q. Is CFN free?

Service is free; you pay for resources created.

Q. Can CFN manage all AWS services?

Most; gaps use custom resources / CDK.

Q. YAML or JSON?

YAML for humans; JSON fine for generators.

Q. StackSets?

One template → many accounts/regions.

Q. Replace Terraform overnight?

No — migrate module by module.

11. Interview Q&A

Q. What is a stack?

A deployed instance of a template.

Q. Change set?

Preview of resource changes before update.

Q. Drift detection?

Find manual changes vs template.

Q. Nested vs cross-stack?

Nested=parent owns children; cross-stack uses Exports/Imports.

Q. Rollback?

Failed create/update returns to prior good state when possible.

Q. CFN vs Terraform state?

CFN state is AWS-managed; TF state is yours (S3/Dynamo).

12. Tips in English, Marathi and Hindi

Ravindra Bagale's Tip (EN)

If you cannot explain the change set in one sentence, do not execute it.

Ravindra Bagale's Tip (MR)

Change set एक वाक्यात समजत नसेल तर execute नका.

Tip (HI)

Change set एक वाक्य में नहीं समझा तो execute मत करना।

Try at home

  1. Run cfn-lint on a sample template.
  2. Draw stack vs change set vs drift.
  3. List three resources you would never edit only in console.

In short

  1. CloudFormation = native AWS IaC stacks.
  2. Change sets and drift keep prod honest.
  3. Parameters/mappings/outputs structure templates.
  4. Pick CFN/CDK/TF based on org constraints.

Revision, interview and comparison cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Revision card: CloudFormation deep basics. Console clicks drift; you need repeatable stacks for VPC, IAM, and apps. CloudFormation is AWS-native IaC: templates declare resources; stacks create/update/delete them as a unit. Write YAML/JSON → create stack → watch events → use change sets before risky updates. A nested stack deploys a shared VPC module used by three app stacks.
Revision card: CloudFormation deep basics · Download PNG · Open card page
Revision card: Change sets before update. Blind stack update can replace a database or break a critical resource. A change set shows adds/modifies/removes before you execute; review replacements carefully. Create change set → inspect → execute only when replacements are expected. Renaming a logical ID shows Delete+Add — stop and use retain/rename strategy.
Revision card: Change sets before update · Download PNG · Open card page
Revision card: Detect drift. Someone changed a security group in the console; the template no longer matches reality. Drift detection compares stack resources to the template and flags unmanaged changes. Run detect-drift on prod weekly; fix by template update or import, not silent console edits. SSH port opened manually shows MODIFIED on the security group resource.
Revision card: Detect drift · Download PNG · Open card page
Revision card: Parameters, mappings, outputs. Hardcoding AMI and account IDs makes one template unusable across envs. Parameters input values; mappings look up by region/env; outputs export values for other stacks. Parameterize InstanceType; map AMI by region; export VPC Id for app stacks. Staging passes t3.micro; prod passes m5.large via the same template.
Revision card: Parameters, mappings, outputs · Download PNG · Open card page
Revision card: Rollback and retention. A failed update can leave you mid-way unless rollback policies are clear. Failed creates roll back by default. Use stack policies, DeletionPolicy, and retain for data stores. Set DeletionPolicy: Retain on RDS; use stack policy to deny delete on prod DB. Bad AMI update rolls back EC2; RDS retained if you delete the stack by mistake.
Revision card: Rollback and retention · Download PNG · Open card page
Comparison: Change set vs Direct stack update. Change set: Shows adds/modifies/replaces before execute. Direct stack update: Applies template changes immediately.
Comparison: Change set vs Direct stack update · Download PNG · Open card page
Comparison: CloudFormation vs Terraform. CloudFormation: Stacks, drift, stack policies baked into AWS. Terraform: Plan/apply, providers beyond AWS, remote state patterns.
Comparison: CloudFormation vs Terraform · Download PNG · Open card page
Interview card: Why change sets?. They preview stack updates so you catch Replace/Destroy before execute. Mandatory habit on prod databases and IAM. Logical ID rename showing Delete+Add → stop.
Interview card: Why change sets? · Download PNG · Open card page
Interview card: What is drift?. Live resource config differs from the template (often from console edits). Detect regularly; fix via IaC. Manual SSH rule on SG → MODIFIED drift.
Interview card: What is drift? · Download PNG · Open card page
Interview card: How do you protect data stores?. DeletionPolicy Retain/Snapshot, stack policies denying delete, careful change sets. Never rely on hope during stack delete. RDS DeletionPolicy Retain survives accidental stack delete.
Interview card: How do you protect data stores? · Download PNG · Open card page
Interview card: Why nested stacks?. Split large templates into reusable modules with clear outputs/imports and smaller blast radius. Update one nested stack without rewriting the whole org template. Shared VPC nested stack consumed by three app stacks.
Interview card: Why nested stacks? · Download PNG · Open card page

More cards: Ravi Sir's Cards.

Practice Tasks

About this scenario

London Legal LLP is a law business in London. Oliver Hughes looks after its IT and cloud work. They count money in GBP and run their AWS resources in the eu-west-2 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 16

Easy List stacks

Why: See what is deployed.

What to do: List stacks in eu-west-2.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Describe stack

Why: Status and outputs.

What to do: Describe stack londonlegal-web.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy Validate template

Why: Catch YAML errors.

What to do: Validate template file://tpl.yaml.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Easy CFN service fee dollars classroom

Why: Service free resources billed.

What to do: CloudFormation service fee in USD for the control plane itself in this classroom (enter 0)?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Min AZs for reliable tip

Why: Reliability pillar.

What to do: Minimum AZs often recommended for prod (enter 2)?

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Easy Run linter before deploy — 1

Why: cfn-lint habit.

What to do: Enter 1 if you should lint templates before deploy.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Medium Stack events

Why: Debug CREATE_FAILED.

What to do: Describe stack events for londonlegal-web.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Detect drift

Why: Find console edits.

What to do: Detect drift on stack londonlegal-web.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Delete stack

Why: Cleanup labs.

What to do: Delete stack londonlegal-lab.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Describe stacks only

Why: Read-only ops role.

What to do: Allow cloudformation:DescribeStacks on all stacks (*).

How:
  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Parameter JSON

Why: Env names as parameters.

What to do: JSON Parameters ProjectName learn.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.

Medium DeletionPolicy retain code 1

Why: Keep data buckets.

What to do: Enter 1 if DeletionPolicy Retain keeps a resource on stack delete.

How:
  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. Click Check answer.

Hard Create change set

Why: Preview prod updates.

What to do: Create change set cs1 on stack londonlegal-web with template file://tpl.yaml.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard Execute change set

Why: Apply after review.

What to do: Execute change set cs1 on londonlegal-web.

How:
  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Hard PassRole for CFN

Why: CFN needs PassRole carefully.

What to do: Allow iam:PassRole on arn:aws:iam::114543297314:role/londonlegal-cfn.

How:
  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Outputs JSON

Why: Export bucket name.

What to do: JSON Outputs BucketName Value my-lab-bucket.

How:
  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. Click Check answer. Key order does not matter.