Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 37 ยท Projects and Practice

Terraform Practice: Ten Exercises with Solutions

Test your Terraform skills with ten graded exercises on state, moved blocks, modules, version constraints, for_each, drift and policy, each with a hint and full solution.

Reading about Terraform and reading Terraform plans are different skills. These ten exercises cover the second half of the tutorial: state, refactoring, modules, workflows and policy. Each has a problem, a hint and a solution. Try each on paper first; the effort is where the learning happens.

HCL cannot run on this site, so the answers are read-only. Three checkers (small Python programs) let you test your logic for the exercises where a computation is involved.

Difficulty is marked from one star (easy) to three stars (hard).

Exercise 1 (one star): rename without destroying

You rename aws_sqs_queue.jobs to aws_sqs_queue.work in code. What does the plan show, and how do you avoid it?

Hint: resources are tracked by address.

Solution. The plan destroys jobs and creates work, because the state still holds the old address. Add a moved block:

HCL
moved {
  from = aws_sqs_queue.jobs
  to   = aws_sqs_queue.work
}

The plan then reports "has moved" and no destroy. See State Commands.

Exercise 2 (one star): read the plan symbols

What do ~, -/+ and <= mean in a plan?

Hint: think update, replace, data.

Solution. ~ is an in-place update, -/+ a replacement (destroy and create) and <= a data source read. Replacements deserve the closest review (Workflow).

Exercise 3 (one star): which version?

Available module versions: 1.0.0, 1.4.2, 1.9.0, 2.0.0, 2.2.1. Which does ~> 1.4 select? And ~> 1.4.0? And >= 1.4, < 2.0?

Hint: ~> lets only the rightmost component rise.

Solution. ~> 1.4 allows >= 1.4, < 2.0: it picks 1.9.0. ~> 1.4.0 allows >= 1.4.0, < 1.5.0: it picks 1.4.2. The range >= 1.4, < 2.0 also picks 1.9.0. See Version Constraints.

Checker 1: version constraint resolver

Edit constraint and available to test your answers for exercise 3.

Python Constraint checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 4 (two stars): fix the index shift

HCL
variable "names" {
  default = ["logs", "assets", "backups"]
}

resource "aws_s3_bucket" "b" {
  count  = length(var.names)
  bucket = "acme-${var.names[count.index]}"
}

You remove "assets". What happens, and what is the fix?

Hint: which indexes change?

Solution. backups moves from index 2 to index 1, so Terraform plans to rename the bucket at [1] and destroy the one at [2]: potentially losing data. Use for_each with stable keys:

HCL
resource "aws_s3_bucket" "b" {
  for_each = toset(var.names)
  bucket   = "acme-${each.key}"
}

Removing assets now destroys only aws_s3_bucket.b["assets"]. To migrate existing state, add moved blocks from b[0] to b["logs"] and so on.

Exercise 5 (two stars): module interface

A module needs vpc_id from another module but both modules call each other's outputs. Terraform reports a cycle. Describe two ways to fix it.

Hint: which resource do both really depend on?

Solution. Find the shared resource (for example a security group) and create it upstream, in the network module or in the root, then pass its ID to both modules. Alternatively merge the two modules if they are really one unit. Do not "fix" the cycle with depends_on; it adds dependencies and cannot remove cycles. See Three-Tier Project.

Exercise 6 (two stars): safe adoption

A bucket acme-legacy exists in AWS, created by hand. Write the code to bring it under Terraform without recreating it, and say what to do next.

Hint: import block.

Solution.

HCL
import {
  to = aws_s3_bucket.legacy
  id = "acme-legacy"
}

resource "aws_s3_bucket" "legacy" {
  bucket = "acme-legacy"
}

Run terraform plan: it shows the import. Compare the plan for other differences (versioning, encryption and tags are separate resources in current AWS provider versions) and add them to the code until the plan shows no unexpected changes; then apply.

Checker 2: plan diff for exercise 4

Python count vs for_each plan

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 7 (two stars): drift

Someone raised desired_capacity of an autoscaling group in the console. Your nightly job reports exit code 2. Give three ways to respond, and say when each is right.

Hint: keep, revert or ignore.

Solution. (1) If the change was intentional and permanent, update the code (desired_capacity) and, if needed, run apply -refresh-only to sync state. (2) If it was a mistake, run a normal apply to revert it. (3) If the value is meant to be managed by autoscaling, add lifecycle { ignore_changes = [desired_capacity] } so it stops appearing. Whatever you choose, record why. See Drift Detection.

Exercise 8 (three stars): safe CI design

Design a pipeline for a repository with envs/dev and envs/prod. Which credentials, triggers and approvals do you use?

Hint: read-only plan, protected apply, OIDC.

Solution. On pull requests: fmt -check, validate, scanners and plan for each changed folder using a read-only OIDC role; post a plan summary. On merge to main: apply dev automatically with a dev-scoped role; apply prod through a protected environment requiring approval, using a prod-scoped role whose trust policy accepts only main. Use a concurrency group per environment with cancel-in-progress: false, -input=false and -lock-timeout. Pin Terraform and providers. See Terraform in CI.

Exercise 9 (three stars): write a policy

Write a rule, in plain logic, that denies any plan creating an aws_s3_bucket_public_access_block with a disabled setting, and any aws_instance without an owner tag. Then implement it below.

Hint: iterate over resource_changes and read change.after.

Solution. Check each change's type; for the block, deny if any of the four flags is not true; for the instance, deny if owner is not in tags.

Python Policy checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Exercise 10 (three stars): split a state

One state holds a VPC and an application. The team wants separate states without recreating anything. Outline the steps.

Hint: state mv/import, backups, order of operations.

Solution. (1) Back up the state (terraform state pull). (2) Create the new configuration and backend for the application, expose the VPC IDs as outputs of the network state and read them with terraform_remote_state or data sources. (3) For each application resource, terraform import it into the new state (or use import blocks), and terraform state rm it from the old state, ideally in one controlled change window with no apply running. (4) Run plan in both configurations until each reports no changes. (5) Remove the moved resources from the old code. Never attempt this while someone else may apply. See Remote State and State Commands.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which block should you add after renaming a resource in code to avoid destroying it?

    moved links the old address to the new one.
  2. 2. Which constraint selects only 1.4.x releases?

    ~> 1.4.0 means >= 1.4.0 and < 1.5.0.
  3. 3. What is the right fix for a count-based list causing replacements?

    Stable keys identify instances independent of order.
  4. 4. A drift check exits with code 2. What does that mean?

    plan -detailed-exitcode: 0 no changes, 1 error, 2 changes.

Summary

  • Renames and refactors need moved blocks; adoption needs import; forgetting needs removed.
  • ~> accepts only rightmost-component increases; test constraints against a version list.
  • Use for_each with stable keys instead of count for distinct items.
  • Resolve cycles by moving the shared resource upstream, not with depends_on.
  • Respond to drift by keeping, reverting or deliberately ignoring, and document the choice.
  • Pipelines need read-only plan roles, protected applies, concurrency control and pinned versions.

Next: Terraform Tutorial Overview