Assignments
25 graded exercises, from your first `terraform apply` to policy-as-code pipelines
How to use these
Do them in order within a level. Work in a throwaway AWS account or sandbox, keep a Git repo with one folder per assignment, and run terraform destroy when you finish each one. Hints are collapsed on purpose: try for 15 minutes first. Assignments 1 to 3 can be done without an AWS account using the random and local providers.
๐ข Beginner
A1. Your first apply with no cloud account ๐ข
Objective: Learn the init, plan, apply and destroy cycle using local providers.
Tasks
- Create a folder with a
versions.tfthat requires Terraform>= 1.9and thehashicorp/randomandhashicorp/localproviders. - Add a
random_petresource and alocal_filethat writes the pet name intohello.txt. - Run
terraform init,plan,apply, then look atterraform.tfstate. - Change the file content in code, run
plan, and read the symbol next to the resource. - Run
terraform destroy.
Expected outcome: hello.txt appears after apply and disappears after destroy. You can explain what +, ~ and -/+ mean in a plan.
Hints
local_fileneedsfilenameandcontent. Reference the pet withrandom_pet.name.id.- A content change on
local_fileshows-/+(replace) because the resource cannot update in place. - Open the state file and find the resource address and its attributes.
Bonus: Add keepers to random_pet and show what makes it regenerate.
A2. Variables, locals and outputs ๐ข
Objective: Parameterise a configuration and expose results.
Tasks
- Add input variables
project(string),environment(string, validated to bedev,stagingorprod) andtags(map of strings). - Create a
localsblock that builds aname_prefixof<project>-<environment>and merges default tags withvar.tags. - Use the prefix in a
local_filename. Add an output for the file path. - Supply values three ways:
terraform.tfvars,-varon the command line andTF_VAR_environment. Note which one wins. - Pass an invalid environment and read the error.
Expected outcome: The validation message appears for bad input. You can state the variable precedence order from memory.
Hints
validation { condition = contains(["dev","staging","prod"], var.environment) error_message = "..." }- Precedence, lowest to highest: defaults, environment variables,
terraform.tfvars,*.auto.tfvars, then-varand-var-file. merge(local.default_tags, var.tags)combines maps, with later maps winning on conflicts.
Bonus: Make one variable sensitive = true and show it is hidden in the plan but present in state.
A3. Read the state like an engineer ๐ข
Objective: Get comfortable with the state commands you will use during incidents.
Tasks
- Using the A1 or A2 project, run
terraform state listandterraform state show <address>. - Run
terraform show -json | jq '.values.root_module.resources[].address'. - Rename a resource in code from
random_pet.nametorandom_pet.mainand runplan. Observe the destroy and create. - Reverse it, then rename using
terraform state mv random_pet.name random_pet.mainand plan again. - Add a
movedblock instead of thestate mvand compare.
Expected outcome: A rename with state mv or moved produces No changes, while a bare rename plans a replacement.
Hints
moved { from = random_pet.name to = random_pet.main }goes in code and is reviewable, which is why we prefer it overstate mv.terraform state rmmakes Terraform forget a resource without deleting it. Do not run it unless you mean it.
Bonus: Back up state with terraform state pull > backup.tfstate and describe when you would use state push.
A4. Provision an S3 bucket on AWS ๐ข
Objective: Create your first real AWS resource safely.
Tasks
- Configure the
awsprovider (~> 6.0) with a region and authenticate with an AWS CLI profile. - Create an S3 bucket with a unique name using
random_idas a suffix. - Add separate resources for versioning, default encryption (SSE-S3) and the public access block.
- Output the bucket ARN. Apply, then confirm with
aws s3api get-bucket-versioning. - Destroy.
Expected outcome: A private, versioned, encrypted bucket exists after apply and is gone after destroy.
Hints
- Since AWS provider v4 these settings are separate resources:
aws_s3_bucket_versioning,aws_s3_bucket_server_side_encryption_configuration,aws_s3_bucket_public_access_block. - Use
force_destroy = truein a lab so destroy works when versioned objects exist. aws sts get-caller-identityconfirms which account you are about to change.
Bonus: Add a lifecycle rule that expires noncurrent versions after 30 days.
A5. Data sources ๐ข
Objective: Reference existing infrastructure without managing it.
Tasks
- Use
aws_caller_identityandaws_regiondata sources and output the account ID. - Use
aws_availability_zonesto list available AZs and output the first two. - Use
aws_amito find the latest Amazon Linux 2023 AMI and output its ID and name. - Use
aws_vpcwithdefault = trueto read the default VPC and its subnets withaws_subnets.
Expected outcome: Outputs show real account, AZ and AMI values. You can explain the difference between a resource and a data block.
Hints
aws_amineedsowners = ["amazon"]and anamefilter likeal2023-ami-2023.*-x86_64.aws_subnetstakesfilter { name = "vpc-id" values = [data.aws_vpc.default.id] }.- Data sources are read during plan, so they must be able to resolve at that time.
Bonus: Explain what happens when a data source depends on a resource that does not exist yet.
A6. EC2 instance with a security group ๐ข
Objective: Deploy a small web server and connect resources by reference.
Tasks
- In the default VPC, create a security group allowing HTTP (80) from anywhere and no SSH.
- Launch a
t3.microAmazon Linux 2023 instance withuser_datathat installs and starts nginx. - Associate the security group and output the public IP.
curlthe IP. Then change theuser_datatext and observe what the plan does to the instance.
Expected outcome: nginx responds on port 80. You can say why user data changes can recreate the instance.
Hints
- Use
vpc_security_group_ids, notsecurity_groups, for VPC instances. - Newer providers replace an instance when
user_datachanges unlessuser_data_replace_on_changeis false. Check the plan before applying. dnf install -y nginx && systemctl enable --now nginxfor AL2023.
Bonus: Use SSM Session Manager (instance profile with AmazonSSMManagedInstanceCore) instead of opening any inbound port for admin access.
A7. count and conditional resources ๐ข
Objective: Create resources conditionally and in repetition.
Tasks
- Add a boolean variable
create_bucketand usecount = var.create_bucket ? 1 : 0on a bucket. - Output the bucket name using a safe expression that works when the count is 0.
- Create three buckets using
count = 3with names derived fromcount.index. - Remove the middle bucket from a list-based
countsetup and observe which resources are replaced.
Expected outcome: You see that removing an item from the middle of a count list shifts addresses and plans unwanted replacements.
Hints
one(aws_s3_bucket.optional[*].id)returnsnullwhen the list is empty.aws_s3_bucket.b[1]is addressed by index, so deleting index 1 renumbers the rest.
Bonus: Rewrite it with for_each = toset(var.names) and show the same removal now only destroys one bucket.
A8. for_each with maps ๐ข
Objective: Create stable, named instances of a resource.
Tasks
- Define a variable
bucketsas a map of objects such as{ logs = { versioning = true }, assets = { versioning = false } }. - Use
for_eachto create buckets, usingeach.keyfor the name andeach.value.versioningto toggle versioning. - Output a map of bucket name to ARN using a
forexpression. - Add a new key and confirm only one resource is added.
Expected outcome: Adding or removing a key never touches the others.
Hints
- Versioning resource:
for_each = { for k, v in var.buckets : k => v if v.versioning }. - Output:
{ for k, b in aws_s3_bucket.this : k => b.arn }. for_eachkeys must be known at plan time.
Bonus: Add a type = map(object({ versioning = optional(bool, false) })) constraint so the field can be omitted.
A9. Formatting, validation and pre-commit ๐ข
Objective: Build the habit of automated hygiene.
Tasks
- Break formatting on purpose, then run
terraform fmt -check -diffandterraform fmt -recursive. - Introduce a reference to an undefined variable and run
terraform validate. - Create a
.gitignorefor Terraform (state,.terraform/, plan files) and commit.terraform.lock.hcl. - Install
pre-commitand add hooks forterraform_fmtandterraform_validate(from theantonbabenko/pre-commit-terraformrepo).
Expected outcome: A commit with bad formatting is rejected locally.
Hints
validateneedsterraform init -backend=falsefirst if you do not want to touch the backend.- Never commit
*.tfstate. Do commit the lock file.
Bonus: Explain why the lock file matters for reproducible builds and what terraform init -upgrade does to it.
A10. A tiny VPC from scratch ๐ข
Objective: Understand the networking resources that every later project builds on.
Tasks
- Create a VPC with one public subnet, an internet gateway and a route table with
0.0.0.0/0to the IGW. - Associate the route table with the subnet.
- Launch an instance in the subnet with a security group allowing HTTP and verify with
curl. - Draw the dependency graph with
terraform graph | dot -Tpng > graph.png.
Expected outcome: The instance is reachable from the internet and the graph shows IGW, route and subnet dependencies.
Hints
- Subnets need
map_public_ip_on_launch = true(or an EIP) for a public IP. - Terraform orders resources by references, so you rarely need
depends_onhere. terraform graphneeds Graphviz (dot) installed.
Bonus: Add a private subnet and a NAT gateway, and explain the cost implication.
๐ก Intermediate
A11. Move state to S3 with locking ๐ก
Objective: Migrate local state to a remote, locked, versioned backend.
Tasks
- Create a state bucket (versioned, encrypted, public access blocked) in a separate bootstrap config.
- Add a
backend "s3"block withuse_lockfile = trueand no bucket value. - Run
terraform init -backend-config="bucket=<name>" -migrate-stateand confirm the prompt. - Verify the object in S3 and that local
terraform.tfstateis now empty. - Start an
applyand leave it at the prompt. In another terminal runterraform planand capture the lock error.
Expected outcome: State lives in S3. The second command fails with Error acquiring the state lock, showing a .tflock object.
Hints
- Native S3 locking requires Terraform 1.11 or newer for the stable behaviour.
- On older versions use
dynamodb_tablewith aLockIDstring hash key. terraform force-unlock <ID>is for dead locks only.
Bonus: Break the lock on purpose by killing a run with kill -9, then recover.
A12. Write a reusable S3 module ๐ก
Objective: Package a secure bucket as a module with a clean interface.
Tasks
- Create
modules/secure-bucketwithmain.tf,variables.tf,outputs.tfandversions.tf. - Inputs:
name,versioning(bool),kms_key_arn(optional),lifecycle_days(number),tags. - Enforce encryption, a public access block and an HTTPS-only bucket policy inside the module.
- Call the module twice from a root with different inputs. Validate inputs with
validationblocks. - Add a
READMEfor the module generated withterraform-docs.
Expected outcome: Two buckets from one module, every input documented, and invalid input is rejected with a helpful message.
Hints
- Use
dynamic "rule"or conditional resources for optional KMS. - Do not put a
providerblock inside a module. Declarerequired_providersonly. - Outputs are the module's public API, so keep them minimal and described.
Bonus: Add a terraform test file for it (see A19).
A13. Dev and prod: tfvars, workspaces or directories ๐ก
Objective: Compare environment strategies and choose one with reasons.
Tasks
- Implement the same small stack three ways: with
-var-fileper environment, with workspaces, and withenvs/devandenvs/prodroot modules. - For each, answer: where does state live, how do you know which environment you are targeting, and how do you vary the backend?
- Deliberately run a destructive command against the wrong environment in the workspace variant to feel the risk.
- Write a one-page decision note recommending an approach for a team of ten.
Expected outcome: A decision note that names isolation, blast radius, review clarity and per-environment permissions as criteria.
Hints
- Workspaces share one backend config and one code path. Directories allow different backends, providers and versions.
- Show the workspace in your prompt with
terraform workspace show, but do not rely on humans noticing. - A common answer: directories per environment and shared modules.
Bonus: Show how Terragrunt or a generator would remove the duplicated root files.
A14. Import an existing resource ๐ก
Objective: Bring hand-made infrastructure under Terraform management.
Tasks
- Create an S3 bucket and an EC2 security group manually in the console or CLI.
- Write
importblocks for them and runterraform plan -generate-config-out=generated.tf. - Clean up the generated code: remove computed or default attributes and replace literals with variables.
- Run
planuntil it saysNo changes. Then apply to record state. - Repeat for one resource with the legacy
terraform importCLI and compare.
Expected outcome: Both resources are managed, and a plan shows no diff.
Hints
import { to = aws_s3_bucket.legacy id = "my-bucket-name" }- Import IDs differ per resource. Check the "Import" section of each resource's docs.
- Generated config is a starting point, not production code.
Bonus: Import a whole VPC with its subnets using for_each in import blocks.
A15. Refactor safely with moved blocks ๐ก
Objective: Restructure code without destroying real infrastructure.
Tasks
- Take a flat config with an
aws_instance.weband a security group. - Move both into a new module
modules/weband addmovedblocks so the plan shows no destroys. - Convert a
count-based resource tofor_eachusingmovedblocks per instance. - Rename a module call and prove the plan is empty.
Expected outcome: Every refactor plan reads has moved or No changes, never destroy.
Hints
moved { from = aws_instance.web to = module.web.aws_instance.this }from = aws_instance.web[0]andto = aws_instance.web["a"]for count to for_each.- Keep
movedblocks in code for a release or two so other states can catch up.
Bonus: Explain how moved differs from terraform state mv and why teams prefer it in review.
A16. Dynamic blocks and for expressions ๐ก
Objective: Generate repeated nested blocks from data.
Tasks
- Define
ingress_rulesas a list of objects (port,cidrs,description). - Build a security group using a
dynamic "ingress"block. - Create an output that groups rule descriptions by port using a
forexpression with...grouping. - Rewrite it with
aws_vpc_security_group_ingress_ruleandfor_each, and explain which approach you prefer.
Expected outcome: Adding a rule to the variable adds exactly one rule to AWS.
Hints
dynamic "ingress" { for_each = var.ingress_rules content { from_port = ingress.value.port ... } }- Separate rule resources avoid the conflict between inline rules and
aws_security_group_rule, and give stable addresses. - Group-by syntax:
{ for r in var.rules : r.port => r.description... }.
Bonus: Use flatten to expand one rule per CIDR.
A17. Lint and scan: fix what tflint and checkov find ๐ก
Objective: Make quality gates part of your daily loop.
Tasks
- Take your A6 or A10 code and run
tflint --init && tflint. - Run
checkov -d .and list the failed checks. - Fix at least five findings in code (encrypted volumes, IMDSv2, restricted egress, descriptions, no public IPs).
- Add two documented skips using inline
#checkov:skip=ID:reasonwith a real justification. - Add a
.tflint.hclwith the AWS ruleset and therecommendedterraform preset.
Expected outcome: Both tools exit clean, and each skip has a written reason.
Hints
- IMDSv2:
metadata_options { http_tokens = "required" }. - Root volume:
root_block_device { encrypted = true }. checkov --compact --quietshortens output.checkov -c CKV_AWS_79runs one check.
Bonus: Output SARIF and upload it to GitHub code scanning.
A18. Plan on PR, comment the result ๐ก
Objective: Build the review half of an IaC pipeline.
Tasks
- Create a GitHub Actions workflow triggered on
pull_requestfor changes underenvs/**andmodules/**. - Run
fmt -check,validate,tflintandterraform plan -no-color. - Post the plan as a PR comment (update the existing comment instead of creating a new one each push).
- Make the checks required with branch protection.
Expected outcome: Every push to a PR updates one comment with the latest plan, and a failing fmt blocks merge.
Hints
- Use
-detailed-exitcodeso you can distinguish no changes (0), changes (2) and errors (1). - Set
terraform_wrapper: falseinsetup-terraformif you pipe output yourself. - To update a comment, find it by a hidden marker like
<!-- tf-plan -->withgithub.rest.issues.listComments.
Bonus: Truncate large plans at about 60,000 characters and attach the full plan as an artifact.
A19. Test your module with terraform test ๐ก
Objective: Add automated tests to a module.
Tasks
- In your secure-bucket module, create
tests/basic.tftest.hcl. - Write a
runblock withcommand = planthat asserts encryption and the public access block are configured. - Write a test that expects failure for an invalid name using
expect_failures. - Write one
command = applytest that creates a real bucket and asserts on its outputs, then runs cleanup automatically. - Run
terraform testlocally and in CI.
Expected outcome: terraform test reports all runs passed.
Hints
run "name" { command = plan assert { condition = ... error_message = "..." } }variables { }inside a run block overrides inputs for that run.mock_provider "aws" {}lets plan-level tests run without credentials.
Bonus: Use a mock_provider so unit tests run without AWS access and keep a single integration test.
A20. Lifecycle rules in practice ๐ก
Objective: Control replacement, protection and drift with lifecycle settings.
Tasks
- Add
prevent_destroy = trueto a bucket and tryterraform destroy. Record the error. - Add
ignore_changes = [desired_capacity]to an ASG, change it in the console, and show plan stays clean. - Add
create_before_destroy = trueto a launch template and a security group that an instance uses, and explain the naming problem it introduces. - Use
replace_triggered_byto recreate an instance when a config file resource changes. - Use
preconditionandpostconditionto validate an AMI architecture.
Expected outcome: You can say when each setting helps and when it hides real problems.
Hints
- With
create_before_destroy, fixed names collide. Usename_prefix. prevent_destroyblocks the whole plan if any resource would be destroyed, not only that resource.ignore_changes = allis almost always a smell.
Bonus: Show terraform apply -replace=aws_instance.web and explain how it replaced the deprecated taint command.
๐ด Advanced
A21. OIDC and least-privilege pipeline roles ๐ด
Objective: Remove long-lived cloud keys from CI and scope what pipelines can do.
Tasks
- Create the GitHub OIDC provider and two IAM roles in Terraform: a read-only plan role and an apply role.
- Restrict the trust policy
subclaim: pull requests for plan, protected environments for apply. - Replace
AdministratorAccesson the apply role with a policy limited to the services your stack uses. Find missing permissions fromAccessDeniedmessages and CloudTrail. - Add a permissions boundary to the apply role so it cannot create IAM admins.
- Prove with a test PR from a branch that the apply role cannot be assumed outside the environment.
Expected outcome: No AWS_ACCESS_KEY_ID stored in GitHub. Assuming the apply role from a PR job fails with Not authorized to perform sts:AssumeRoleWithWebIdentity.
Hints
- Subjects look like
repo:ORG/REPO:pull_request,repo:ORG/REPO:ref:refs/heads/mainandrepo:ORG/REPO:environment:prod. - Use
StringEqualsfor exact subs andStringLikeonly when you need wildcards. - Use IAM Access Analyzer policy generation from CloudTrail to draft the least-privilege policy.
Bonus: Add aud and job_workflow_ref conditions so only your reusable workflow can assume the role.
A22. Split state and share data across stacks ๐ด
Objective: Reduce blast radius by splitting one big state into layers.
Tasks
- Take the lab project and split it into
network(VPC) andapp(ALB + ASG) stacks with separate state keys. - Publish network outputs through SSM Parameter Store from the network stack and read them in the app stack with data sources. Then do the same with
terraform_remote_stateand compare. - Migrate existing resources between states without recreating anything, using
terraform state mv -state-outorremovedandimportblocks. - Document the apply order and enforce it in the pipeline with job dependencies.
Expected outcome: Both stacks plan clean with no resource recreation. The app stack can be applied without write access to the network state.
Hints
- Back up both states before touching anything:
terraform state pull > backup.tfstate. removed { from = aws_vpc.this lifecycle { destroy = false } }drops a resource from state without destroying it.terraform_remote_stateexposes all outputs and requires read access to the whole state file, which is why SSM or a data lookup is often safer.
Bonus: Describe how you would handle a circular dependency between two stacks.
A23. Scheduled drift detection and remediation policy ๐ด
Objective: Find out-of-band changes automatically and decide how to respond.
Tasks
- Create a scheduled GitHub Actions workflow (
cron) that runsterraform plan -detailed-exitcode -refresh-onlyfor each environment. - On exit code 2, open or update a GitHub issue with the plan summary and notify Slack through a webhook secret.
- Create real drift: change a security group rule in the console and an ASG size with the CLI.
- Write a policy for each case: revert via apply, codify the change, or import and then codify.
- Add ignore rules for fields that legitimately change (for example
desired_capacityunder autoscaling).
Expected outcome: A scheduled run opens an issue that shows the drifted attributes within one cycle.
Hints
- Exit codes:
0no changes,1error,2changes present. - Use
terraform show -no-coloron a saved plan to build a short summary. - Use read-only credentials for the drift job so it can never change anything.
Bonus: Add an AWS Config or CloudTrail rule that alerts on manual changes to tagged resources.
A24. Versioned module registry and a safe upgrade path ๐ด
Objective: Publish modules like a product and upgrade consumers without surprises.
Tasks
- Move the VPC module to its own repository with semantic version tags (
v1.0.0). - Consume it with
source = "git::https://github.com/ORG/terraform-aws-vpc.git?ref=v1.0.0"from dev and prod. - Make a backwards-compatible change (
v1.1.0) and a breaking one (v2.0.0, for example renaming an input with amovedblock for resources). - Upgrade dev first, review the plan, then prod. Record what the plan showed.
- Add module tests and a CI release workflow that runs them before tagging.
- Add a
CHANGELOG.mdand describe the support policy.
Expected outcome: Dev and prod pin different versions during a rollout, and the v2 upgrade plan shows no destroys thanks to moved blocks.
Hints
- Use
terraform init -upgradeafter changing aref. - Constrain registry modules with
version = "~> 1.1". Git sources only support?ref=. - Keep
movedblocks for at least one major version.
Bonus: Publish to a private registry (Terraform Cloud, or a Git-based internal one) and compare the experience.
A25. Policy as code and cost guardrails in the pipeline ๐ด
Objective: Add automated approval rules on top of the plan.
Tasks
- Export the plan as JSON:
terraform plan -out=tfplan && terraform show -json tfplan > plan.json. - Write three OPA (Rego) policies and run them with
conftest test plan.json: deny security groups open to0.0.0.0/0on port 22, require tagsOwnerandEnvironment, and deny instance types outside an allow-list. - Add Infracost to the PR workflow to comment the monthly cost change and fail if a PR adds more than a threshold.
- Make the pipeline fail with a clear message for each policy and show both a failing and a passing PR.
- Document how an exception is requested and approved.
Expected outcome: A PR that opens SSH to the world is blocked automatically, and each PR shows its cost delta.
Hints
- Look at
resource_changes[]in the plan JSON, and usechange.afterfor the planned values. conftest test --policy policy/ plan.jsonreturns a non-zero exit ondeny.- Run policies against the plan, not just the source, so module output and computed values are covered.
Bonus: Write the same policy in Sentinel or Checkov custom checks and compare maintenance cost.