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

AWS Cloud

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.

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?

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?

A template describes which resources you want and how they are connected. A stack is the deployed group CloudFormation manages from that template. In this lab the template declares a bucket. A parameter can supply an environment name, the resource section defines the bucket settings, and an output can give you the resulting bucket name. Read the output after a successful create and match that name in S3. The name in the running account is what an application would use.

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
Apply an infrastructure change deliberatelyTemplate: Describes the desired resources; Change set: Shows the proposed difference; Review: Inspect replacements and permissions; Execute update: CloudFormation applies the change; Monitor: Read events and verify the workloadTemplateDescribes the desired resourcesChange setShows the proposed differenceReviewInspect replacements and permissionsExecute updateCloudFormation applies the changeMonitorRead events and verify the workload
Preview then apply

4. How to work safely

A change set is your preview before updating the stack. If it says the lab bucket will be replaced rather than modified, ask why and what will happen to existing data. A replacement can give an app a different physical resource, even though it still uses the same logical name in the template. Check the resource event and output after any update. Keep a note of the old name so you can verify whether the resource stayed or changed.

  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

Look for a completed stack event and an output bucket name. Open the named bucket in the lab account and confirm the displayed encryption setting matches the template. Remove any test objects before cleanup if the exercise put them there. After stack deletion, read its events and check that the named disposable bucket was removed, or that a retention policy explains why it remains.

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

  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.

Practise this chapter

Interview questions and answers

A change set says a storage resource will be replaced. What do you check before executing it?

Find the property forcing replacement, note the affected physical resource and check data retention and application references. Compare the proposed new resource to the intended settings. After applying in the lab, use stack events and outputs to verify exactly what changed.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which CloudFormation part describes the actual AWS resources to manage?

Answer and explanation

B. The Resources section of the template

Resources declare the resource types and settings. The stack tracks the deployed set.

2. What is a change set for?

Answer and explanation

C. Previewing proposed stack changes before executing them

Review proposed actions, especially replacements, before any stack update is applied.

3. A lab stack was deleted but its bucket remains. What should you inspect?

Answer and explanation

C. Its retention policy and the deletion events

The events and policy explain whether CloudFormation intentionally retained the resource or encountered a deletion issue.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

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

See what is deployed.

List stacks in eu-west-2.

  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

Status and outputs.

Describe stack londonlegal-web.

  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

Catch YAML errors.

Validate template file://tpl.yaml.

  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

Service free resources billed.

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

  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

Reliability pillar.

Minimum AZs often recommended for prod (enter 2)?

  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 Apply the lesson: scenario 6

Before deploying a CloudFormation template, which named linting tool can catch template issues? Enter the tool name.

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Medium Stack events

Debug CREATE_FAILED.

Describe stack events for londonlegal-web.

  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

Find console edits.

Detect drift on stack londonlegal-web.

  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

Cleanup labs.

Delete stack londonlegal-lab.

  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

Read-only ops role.

Allow cloudformation:DescribeStacks on all stacks (*).

  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

Env names as parameters.

JSON Parameters ProjectName learn.

  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 Apply the lesson: scenario 12

A stack is deleted, but its bucket must remain. Which DeletionPolicy value expresses that intent?

  1. Read the situation and identify what you need to decide.
  2. Work through the relevant concept or calculation.
  3. Enter only the requested term or number.
  4. Check your answer, then read the explanation.

Hard Create change set

Preview prod updates.

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

  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

Apply after review.

Execute change set cs1 on londonlegal-web.

  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

CFN needs PassRole carefully.

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

  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

Export bucket name.

JSON Outputs BucketName Value my-lab-bucket.

  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.