Exercises — Module 9: Terraform (IaC)
Environment: Terraform installed locally, AWS account with the Module 8 money rules active. Every exercise repo gets
.gitignorewith*.tfstate*,.terraform/on line one — before your first commit. The habit of reading EVERY plan fully is the skill being trained here; never type "yes" to a plan you haven't narrated out loud.
Part A — Warm-Up Drills
Drill 1 — The loop, minimal. Single main.tf creating one S3 bucket (random suffix via random_pet resource). Run: init → plan (read it aloud) → apply → plan again (empty — why?) → destroy.
✓ You can explain what each of the five commands did and where state appeared.
Drill 2 — Plan-reading reps. With the bucket applied: (a) add a tag → plan shows ~ update in-place; (b) change the bucket NAME → plan shows -/+ destroy and then create replacement. Stop. Explain why (b) is destructive, what it would mean for a bucket full of data, and which attribute changes force replacement (hint: the docs mark them "forces new resource").
✓ You now instinctively scan plans for the -/+ symbol.
Drill 3 — State peeking. terraform state list; state show on the bucket; open terraform.tfstate in an editor (read-only!) and find the bucket's ID and attributes. Then terraform console and evaluate aws_s3_bucket.demo.arn.
✓ State demystified: it's just a JSON map of your names → real IDs.
Drill 4 — Variables three ways. Add variable "env" with validation (dev/staging/prod only). Supply it via: terraform.tfvars, -var, and TF_VAR_env. Then supply an invalid value and read the validation error.
✓ You can state the precedence order from memory.
Drill 5 — fmt & validate reflex. Mangle your file's indentation and add a typo'd attribute. Run terraform fmt (fixes style) then validate (catches the typo). Add both to a pre-commit habit or Makefile.
Part B — Guided Labs
Lab 1 — Remote State + Locking (60 min)
- Manually (console/CLI — the one-time bootstrap exception): S3 bucket
yourname-tfstate(versioning ON) + DynamoDB tabletf-locks(keyLockID). - Add the s3 backend block to Drill 1's project;
terraform init -migrate-state; confirm local tfstate is now a stub and the real one sits in S3. - See the lock work: run
terraform applybut DON'T confirm; from a second terminal runterraform plan— read the lock error, identify who holds it. Release and rerun. - Delete a resource from state ON PURPOSE (
state rm), run plan — Terraform wants to create a duplicate. Fix withimport. ✓ You've now experienced why state is sacred AND how to repair it — before it ever happens for real.
Lab 2 — Variables, Locals, Outputs: a Parametrized Stack (90 min)
- Project: SG + EC2 instance, with variables
env,instance_type(default t3.micro),allowed_ssh_cidr; locals forname_prefixandcommon_tags; outputs for public IP and SSH command string. dev.tfvarsandprod.tfvars(prod: bigger type, tighter CIDR). Plan with each and DIFF the two plans by eye.- Mark a
db_passwordvariablesensitive = true; output it once without sensitive on the output (error!), then with — see the redaction in plan and the plaintext in state. Write the two-line conclusion about secrets in state. ✓ Same code, two shapes, secrets behavior understood empirically.
Lab 3 — count vs for_each: Feel the Index Shift (60 min) — the famous footgun
- Create 3 S3 buckets with
countover a list["alpha","bravo","charlie"]. - Remove
"bravo"(the MIDDLE item) from the list. Run plan and read carefully: charlie's bucket gets DESTROYED and RECREATED (index shift!). Do NOT apply. Screenshot the plan. - Refactor to
for_eachover a set of the same names (import or recreate cleanly). Remove bravo again → plan touches ONLY bravo. ✓ The two plans side by side in your notes = the definitive interview answer for "count vs for_each."
Lab 4 — Modules: Wrap the Module-4 VPC (2 h)
- Use the registry module
terraform-aws-modules/vpc/aws(pin the version!) to create your standard VPC: 2 public + 2 private subnets, NAT (single, to save cost — note thesingle_nat_gatewayflag), tags from locals. - Read the plan slowly — count how many resources ~15 lines of yours created. Apply. Compare against your hand-built Module 4 VPC in the console: identical shape?
- Now WRITE a module:
modules/web-sg/takingvpc_idandingress_ports(list), producing a security group with adynamic "ingress"block; outputs the SG id. Consume it from root twice (web: 80,443; admin: 22). ✓ You've consumed and authored modules, and used dynamic blocks for real. - Destroy the NAT/VPC when done — leave the state infrastructure (bucket/lock table) forever.
Lab 5 — Import Day: Adopt ClickOps (60 min)
- In the console, hand-create a "legacy" resource: an S3 bucket with a couple of tags (pretend a predecessor left it).
- Adopt it:
importblock +terraform plan -generate-config-out=generated.tf; review the generated code, trim the noise, move it into your main files, re-plan until zero changes. - Write the runbook you just followed as 5 bullet points — this is a real day-one task at brownfield companies.
✓
terraform plansays "No changes" on a resource Terraform didn't create.
Lab 6 — Drift & Guardrails (45 min)
- With Lab 2's stack applied: in the CONSOLE, change the instance's tag and add a rogue SG rule (simulate a colleague's hotfix).
terraform plan— read the drift detection. Decide per-change: revert (apply) or adopt (update code)? Do one of each.- Add
lifecycle { prevent_destroy = true }to a "precious" resource; tryterraform destroy; read the refusal. Then addcreate_before_destroysomewhere and explain when it matters (hint: things referenced by others, e.g. launch configs). ✓ You can demo drift detection and name the two lifecycle guardrails cold.
Lab 7 — Terraform in CI + Atlantis Taste (90 min)
- GitHub Actions on PR: fmt-check → validate → tflint → trivy config scan →
planposted as a PR comment (use a plan-comment action or a scripted step); apply job only on merge to main, gated by an environment approval, authenticated via the Module 8 OIDC role (no keys!). - Open a PR adding one tagged resource; review your own plan comment as if you were the approver; merge; watch apply.
- Optional but recommended: run the Atlantis container locally against a test repo (webhook via a tunnel); do one
atlantis plan/atlantis applycomment cycle. Write 3 sentences on what Atlantis adds over your Actions setup. ✓ No laptop ever runs apply against shared state again.
Part C — Challenges
C1 — Rebuild Module 8's Lab 4 as code. ECR + ALB + ECS Fargate service + SG chain + Secrets Manager reference, consuming Lab 4's VPC via terraform_remote_state. Success = your app serving through the ALB, terraform destroy leaves a clean account. (This is the capstone-grade challenge — take a weekend.)
C2 — Workspaces vs directories. Implement the same tiny stack both ways: (a) terraform workspace dev/prod, (b) envs/dev + envs/prod directories with separate state keys. Write a paragraph on which you'd choose for a team and why.
C3 — Data-source treasure hunt. Using ONLY data sources (no resources): output the latest Ubuntu 24.04 AMI id, your account id, the default VPC's id, and the AZ names in your region.
C4 — Conditional infra. A variable enable_bastion (bool) that creates the bastion instance + SG only when true (count = var.enable_bastion ? 1 : 0) — and handle the outputs gracefully when it's off (one() or splat).
C5 — The 100-tag sweep. Write a default_tags block on the provider so EVERY resource gets ManagedBy/Env/Owner automatically; prove it by planning an untagged resource and seeing tags appear.
C6 — State surgery under pressure. Rename aws_instance.web to aws_instance.frontend in code. Plan shows destroy+create. Fix with state mv so the plan goes to zero. Then do the same rename the modern way with a moved {} block and compare.
Part D — Break & Fix Scenarios
D1 — The lost state (sandbox!). Local-state project with 2 resources; delete terraform.tfstate; run plan. Recover the situation two ways: re-import both, OR restore from the S3 versioned backup (if using Lab 1's backend — that's WHY versioning was on). Time both paths.
D2 — The stuck lock. Kill a terraform apply mid-run (Ctrl+C twice / close terminal). Next plan: lock error. Inspect the DynamoDB item, then terraform force-unlock <id> — and write the one question you must answer before force-unlocking on a team (is anyone actually running?).
D3 — Version pin missing. Remove provider version constraints, rm -rf .terraform, re-init — note what version you silently got. Explain how an unpinned provider once broke someone's Friday (plan diffs from provider behavior changes), then pin with ~> and commit .terraform.lock.hcl.
D4 — The apply that half-failed. Create a plan with 3 resources where the 2nd fails (e.g., an SG rule referencing a bogus CIDR like "999.0.0.0/8" passes validate but fails apply — or use an IAM name collision). Observe: resource 1 EXISTS, state is partial. Run plan again and understand that Terraform simply continues — "failed apply" ≠ "rolled back." Fix and converge.
D5 — Secrets leak audit. grep your state file for a known password string. Found it? Now write your team policy in 3 bullets: state bucket encryption+access, sensitive vars, and pulling secrets at runtime instead (SSM/Secrets Manager data sources).
Part E — Interview Rehearsal (out loud)
- What problem does Terraform solve over the console and over bash+AWS CLI scripts?
- Explain state: what's in it, why remote+locked, what happens if it's lost or leaked.
- Plan shows
-/+on an RDS instance. Walk me through your next 5 minutes. - count vs for_each — tell the index-shift story with your Lab 3 evidence.
- How do you adopt existing click-created infrastructure? (Your Lab 5 runbook.)
- How does Terraform fit into CI/CD? What does Atlantis add?
- Where do secrets live relative to Terraform? Why is
sensitive = truenot enough? - Terraform vs Ansible vs Helm — one sentence each, and where they hand off.
Done when
you narrate plans aloud by reflex, Lab 3's side-by-side screenshot exists, Lab 5 reached "No changes," D1's recovery was timed both ways, and C1 builds + destroys cleanly with a $0 bill the next day.
