Terraform & Infrastructure as Code Roadmap

Describe servers, networks and databases as code, preview every change with a plan and rebuild whole environments with one command: 27 topics in four stages, from your first terraform apply to modules, remote state, tests, CI/CD pipelines and OpenTofu. Each topic has what to learn, free resources and a hands-on task that costs nothing. Tick things off as you go; your progress is saved in this browser. Use the filter to focus on core IaC skills, the topics of the Terraform Associate exam, or running Terraform in teams and production.

The roadmap in detail

Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice. Everything here applies to OpenTofu too: swap terraform for tofu.

Stage 1 · Beginner Terraform basics

Learn what infrastructure as code is, the plan/apply workflow and the HCL language. You don't need a cloud account for this stage: the local, random and docker providers run entirely on your own computer.

What infrastructure as code is, and the alternatives

Infrastructure as code (IaC) means describing servers, networks, DNS records and databases in text files instead of clicking through a console. The files live in Git, so every change is reviewed in a pull request, has an author and a reason, and can be repeated exactly: the same code builds a test environment today and production tomorrow. Terraform is declarative: you write the end state you want ("three subnets and one bucket") and Terraform works out the API calls to get there, instead of you writing the steps.

Terraform talks to almost any platform through providers (AWS, Azure, Google Cloud, Kubernetes, GitHub, Cloudflare and thousands more), which is its main strength. The alternatives: AWS CloudFormation (AWS only, state managed by AWS), the AWS CDK and Pulumi (real programming languages such as TypeScript or Python), and OpenTofu (the open-source fork of Terraform, covered in stage 4). Ansible overlaps a little, but it is mainly a configuration tool: Terraform creates the machines, Ansible configures what runs on them.

What to learn

  • The problems IaC solves: repeatability, review, drift, documentation, disaster recovery
  • Declarative vs imperative tools, and what "desired state" means
  • Provisioning (Terraform, CloudFormation) vs configuration management (Ansible)
  • How Terraform handles multi-cloud and non-cloud services through providers
  • When CloudFormation, the AWS CDK or Pulumi might be a better fit

Free resources

Practice

Write down, in a few sentences, how you would rebuild one thing you set up by hand (a VM, a DNS record, a GitHub repository's settings) if it vanished tomorrow. Keep the note: by the end of stage 2 you will have turned it into code. The DevOps roadmap's IaC topic shows where this fits in the bigger picture.

Install Terraform and the core workflow: init, plan, apply, destroy

Terraform is a single binary. Install it from HashiCorp's package repository or with a version manager such as tfenv, and check it with terraform version. Every project is a folder of .tf files (the working directory). The workflow is always the same: terraform init downloads providers and modules and sets up the backend; terraform plan compares your code with what exists and shows what it would create (+), change (~) or destroy (-); terraform apply makes the changes after you confirm; terraform destroy removes everything the configuration manages.

Read every plan. A line saying -/+ must be replaced means a resource will be destroyed and recreated, which for a database means data loss. Save a plan with terraform plan -out=tfplan and apply exactly that plan with terraform apply tfplan. Two helpers keep code clean: terraform fmt fixes formatting and terraform validate checks syntax and references without touching any real infrastructure.

What to learn

  • Install Terraform and check it with terraform version
  • init, plan, apply, destroy and what each one touches
  • Reading plan symbols: + create, ~ update in place, -/+ replace, - destroy
  • Saved plans: plan -out and apply tfplan
  • terraform fmt, terraform validate and terraform -help
  • What goes in .gitignore: .terraform/, *.tfstate, *.tfvars with secrets (but commit .terraform.lock.hcl)

Free resources

Practice

Follow the Docker get-started tutorial: run an nginx container with the kreuzwerker/docker provider, change its port, read the plan, apply, then terraform destroy. Put the folder under Git with a proper .gitignore.

HCL: the Terraform language

Terraform code is written in HCL (HashiCorp Configuration Language). Everything is a block with a type, zero or more labels and a body: resource "aws_s3_bucket" "logs" { bucket = "my-logs" }. Inside a body you set arguments (name = value) and nest more blocks. Terraform reads every .tf file in the folder as one configuration, so file names are just for people; the usual layout is main.tf, variables.tf, outputs.tf, providers.tf and versions.tf.

Values have types: string, number, bool, and collections list(...), set(...), map(...), object({...}) and tuple([...]). Strings support interpolation: "web-${var.env}". Comments use #, // or /* */. Multi-line text uses heredocs (<<-EOT). Order of blocks doesn't matter: Terraform builds a dependency graph from references, not from the order you write things in.

What to learn

  • Blocks, labels, arguments and nested blocks
  • Primitive and complex types: list, set, map, object, tuple
  • String interpolation, heredocs and comments
  • The terraform {} block and the conventional file layout
  • The official style guide: naming with underscores, fmt, one resource type per purpose

Free resources

Practice

With the local provider, write a configuration that creates a text file using local_file, with the content built from a heredoc and an interpolated value. Break the syntax on purpose and read terraform validate's error message.

Providers and version constraints

A provider is a plugin that knows one platform's API. You declare which providers you need, and from where, in required_providers inside the terraform {} block, for example aws = { source = "hashicorp/aws", version = "~> 6.0" }, then configure them in a provider "aws" { region = "eu-west-1" } block. terraform init downloads them from the Terraform Registry and records the exact versions and checksums in .terraform.lock.hcl, which you commit so everyone uses the same build.

Version constraints protect you from surprise breaking changes: ~> 6.0 allows any 6.x but not 7.0, >= 1.12, < 2.0 sets a range, and required_version pins the Terraform CLI itself. Upgrade on purpose with terraform init -upgrade. Need the same provider twice, for example two AWS regions? Give the second block an alias and pass provider = aws.us_east_1 to the resources that need it.

What to learn

  • required_providers with source and version, and required_version
  • Version constraint operators: =, !=, >=, ~>
  • The dependency lock file and terraform init -upgrade
  • Provider configuration and credentials (environment variables, profiles, never hard-coded keys)
  • Several configurations of one provider with alias

Free resources

Practice

Add the random and local providers with ~> constraints, run init and read the lock file. Loosen a constraint, run init -upgrade and see what changes in the lock file with git diff.

Resources, data sources and references

A resource block is something Terraform creates and manages: resource "aws_instance" "web" {...}. The first label is the type (which starts with the provider name), the second is your local name, and together they form the address aws_instance.web. A data source only reads something that already exists, such as the latest Ubuntu AMI or a VPC made by another team: data "aws_ami" "ubuntu" {...}, referenced as data.aws_ami.ubuntu.id.

Resources refer to each other's attributes: subnet_id = aws_subnet.public.id. Some attributes, such as an ID, are only known after apply and show as (known after apply) in the plan. The lifecycle block changes how Terraform treats a resource: prevent_destroy blocks accidental deletion, create_before_destroy avoids downtime on replacement, and ignore_changes stops Terraform fighting with something that changes outside it.

What to learn

  • Resource syntax, resource addresses and the provider's docs page for each type
  • Data sources, and when to read rather than create
  • Referencing attributes across resources, and "known after apply"
  • lifecycle: prevent_destroy, create_before_destroy, ignore_changes, replace_triggered_by
  • Why provisioners (local-exec, remote-exec) are a last resort

Free resources

Practice

Generate a name with random_pet, then use it in a local_file resource and in a second file's content, so one resource references another. Add prevent_destroy to one of them and try terraform destroy.

Variables, outputs and locals

Input variables make code reusable: variable "env" { type = string, default = "dev" }, used as var.env. Set values in a terraform.tfvars or *.auto.tfvars file, with -var-file=prod.tfvars or -var on the command line, or with TF_VAR_env environment variables. When the same variable is set in several places, the later source wins: command-line flags beat tfvars files, which beat environment variables and defaults.

Add a validation block to reject bad values early, and sensitive = true to hide a value from plan output (it is still stored in state). Outputs print values after apply and pass data out of modules: output "url" { value = aws_lb.web.dns_name }, read with terraform output. Locals name an expression you use several times, such as a common set of tags: local.common_tags.

What to learn

  • Declaring variables with type, default, description and nullable
  • Ways to set values and their precedence (tfvars, -var, TF_VAR_)
  • validation blocks with a condition and error_message
  • sensitive variables and outputs, and their limits
  • Outputs, terraform output -json, and locals

Free resources

Practice

Turn your Docker nginx project into a configurable one: variables for the container name and port (with a validation that the port is between 1024 and 65535), a dev.tfvars and a prod.tfvars, and an output with the URL. Check the precedence by setting the same variable with TF_VAR_ and -var.

Am I ready? Stage 1 quiz

Which command shows what Terraform would change, without changing anything?

  1. terraform init
  2. terraform plan
  3. terraform validate
  4. terraform show

Plan compares your configuration with the state and the real infrastructure and prints the proposed changes. Nothing is created until you apply.

A provider constraint says version = "~> 6.2". Which version is allowed?

  1. 5.9.0
  2. 7.0.0
  3. 6.1.4
  4. 6.9.1

~> 6.2 means "6.2 or newer, but below 7.0": only the rightmost given number may increase.

What is the difference between a resource and a data block?

  1. A resource is created and managed by Terraform; a data source only reads something that already exists
  2. Data blocks are for databases only
  3. Resources are read-only, data blocks create things
  4. There is none; they are aliases

Data sources look things up (an AMI, a VPC made elsewhere) so you can reference them without managing them.

Which file should you commit to Git?

  1. .terraform/
  2. terraform.tfstate
  3. .terraform.lock.hcl
  4. secrets.tfvars

The lock file pins provider versions and checksums for everyone. The .terraform folder is a download cache, state belongs in a remote backend, and secrets never go in Git.

A plan line reads -/+ resource "aws_db_instance" "main" (must be replaced). What does that mean?

  1. The database will be updated in place with no downtime
  2. The database will be destroyed and a new one created
  3. Terraform will only refresh the state
  4. The resource is being imported

-/+ is a replacement. For a database that can mean data loss, so stop and find out which argument forces it.

Stage 2 · Real configurations Expressions, dependencies and state

Write configurations that scale from one resource to fifty, understand how Terraform orders its work, and learn state: the part of Terraform that causes the most trouble when it is misunderstood. The stage ends with a real (free tier) AWS project.

Expressions: count, for_each, for, conditionals and dynamic blocks

To create several similar resources, use a meta-argument. count = 3 makes a list addressed as aws_instance.web[0], and is handy for "zero or one" switches: count = var.enabled ? 1 : 0. for_each takes a map or set of strings and addresses each copy by key, aws_s3_bucket.this["logs"], using each.key and each.value. Prefer for_each for anything with identity: if you remove the middle item of a count list, every later item shifts index and Terraform wants to replace them.

For expressions transform collections: [for s in var.subnets : s.cidr] or {for u in var.users : u.name => u.role}. The conditional cond ? a : b picks a value, splat aws_instance.web[*].id collects one attribute from a list, and a dynamic block generates repeated nested blocks, such as one ingress rule per item in a variable.

What to learn

  • count and count.index, including the 0-or-1 pattern
  • for_each with maps and sets, each.key / each.value, and why it beats count for named things
  • For expressions for lists and maps, with an if filter
  • Conditional expressions and splat expressions
  • dynamic blocks, and when they make code harder to read

Free resources

Practice

Create three Docker containers (or three local_files) with count, remove the middle one from the list and read the plan. Rewrite it with for_each over a map and repeat: only one resource should be destroyed this time.

Built-in functions and terraform console

Terraform has a fixed set of built-in functions; you can't define your own in plain HCL. The ones you'll use most: merge() for combining tag maps, lookup() and try() for optional values, length(), join() / split(), format(), cidrsubnet() for carving a VPC range into subnets, jsonencode() for IAM policies, yamldecode() and file() for reading data files, and templatefile() for rendering scripts and config files.

terraform console is an interactive prompt where you can try any expression against your current configuration and state, which is the fastest way to learn functions and debug a tricky for expression.

What to learn

  • Collection functions: merge, concat, flatten, lookup, keys, values
  • String and encoding functions: format, join, jsonencode, yamldecode
  • Network functions: cidrsubnet and cidrhost
  • templatefile and file, and try / can for safe lookups
  • Experimenting in terraform console

Free resources

Practice

In terraform console, split 10.0.0.0/16 into four /20 subnets with cidrsubnet, then check the results in our CIDR calculator. Render a small startup script with templatefile into a local_file.

Dependencies and the resource graph

Terraform builds a dependency graph from your references. If a subnet uses aws_vpc.main.id, Terraform knows the VPC must exist first; that's an implicit dependency. Anything without a dependency between them is created in parallel (10 operations at a time by default, set with -parallelism). On destroy, the graph is walked in reverse.

Sometimes a dependency is real but invisible in the code, for example an app that needs an IAM policy attached before it starts. Then add depends_on = [aws_iam_role_policy.app], an explicit dependency. Use it sparingly: it makes plans more conservative. terraform graph prints the graph in DOT format if you want to see it.

What to learn

  • Implicit dependencies from references
  • depends_on for hidden dependencies, and why to avoid overusing it
  • Parallel creation and the -parallelism flag
  • Destroy order, and dependency cycles (and how to break them)
  • terraform graph

Free resources

Practice

Build a Docker network and two containers attached to it. Run terraform graph and draw it (or paste it into any Graphviz viewer). Then create a cycle on purpose (two resources referencing each other) and read the error.

State: what it is and how to change it safely

Terraform remembers what it created in a state file (terraform.tfstate, JSON). It maps each resource address in your code to a real object ID, caches attributes and records dependencies. Every plan refreshes the state from the real world, then compares it with your code. State can contain secrets in plain text (database passwords, private keys), so treat it as sensitive, and never edit it by hand.

Use the CLI instead. terraform state list and state show inspect it; state mv and state rm change it. Modern Terraform prefers code over commands: an import block (Terraform 1.5+) adopts an existing object, with terraform plan -generate-config-out=generated.tf writing the code for you; a moved block renames or relocates a resource without destroying it; a removed block stops managing something without deleting it. Because they are code, they go through review like any other change. terraform apply -replace=ADDRESS forces one resource to be recreated, and plan -refresh-only updates state to match reality without changing infrastructure.

What to learn

  • What state stores and why Terraform needs it
  • terraform state list, show, mv, rm and terraform show
  • import blocks and -generate-config-out
  • moved and removed blocks for refactoring
  • -replace and -refresh-only
  • Why state is sensitive and must never be committed

Free resources

Practice

Start a container by hand with docker run, then adopt it with an import block and -generate-config-out. Rename a resource with a moved block and confirm the plan shows no destroy. Finally, stop managing one resource with a removed block and check it still exists.

Remote state, backends and locking

Local state works only while one person on one laptop runs Terraform. A backend stores state remotely so the whole team and CI share it. On AWS the usual choice is the S3 backend: a versioned, encrypted bucket. Since Terraform 1.11, S3 can lock state natively with use_lockfile = true, which writes a .tflock object next to the state so two applies can't run at once. The older DynamoDB locking (dynamodb_table) is deprecated in Terraform; OpenTofu supports both methods and says it has no plans to deprecate either.

Backend blocks can't use variables, so teams pass per-environment settings with terraform init -backend-config=prod.hcl. Changing the backend and running init -migrate-state copies state across. Another configuration can read your outputs with the terraform_remote_state data source, though passing values through SSM parameters or data sources keeps configurations less tightly coupled. If a crashed run leaves a lock behind, terraform force-unlock LOCK_ID removes it; be sure nobody is actually running first.

What to learn

  • Why local state fails for teams, and what a backend does
  • The S3 backend: bucket versioning, encryption, key per configuration
  • State locking with use_lockfile = true (and recognising the deprecated DynamoDB setup in older code)
  • Partial backend configuration with -backend-config, and init -migrate-state
  • terraform_remote_state and force-unlock

Free resources

Practice

Free option: run LocalStack in Docker and point an S3 backend at it. Or use the AWS free tier: create a versioned, encrypted bucket, move your state into it with init -migrate-state and use_lockfile = true, then run plan in two terminals at once and watch the second one wait for the lock. See AWS S3 for bucket basics.

Project: a small AWS network and server in Terraform

Time to put it together on a real cloud. Build a VPC with public and private subnets across two Availability Zones, an internet gateway and route tables, a security group, and one small EC2 instance that serves a web page through a user-data script. Look up the AMI with a data source, use for_each for the subnets and cidrsubnet for their ranges, and output the public URL.

Use the hashicorp/aws provider's docs for every resource, set default_tags in the provider block so everything is labelled, and run Terraform as an IAM user or role with only the permissions it needs. Avoid NAT gateways and load balancers while learning: they cost money every hour. When you're done, terraform destroy and check the console is empty.

What to learn

  • Authenticate the AWS provider safely (profiles or SSO, not hard-coded keys)
  • VPC, subnets, route tables and an internet gateway in code
  • Security groups and an EC2 instance with user data from templatefile
  • default_tags on the provider
  • Destroy everything and check the bill

Free resources

Practice

Build it on the AWS free tier, open the URL, then terraform destroy the same day. Rebuild it from scratch with one apply to prove the code is complete. Background reading: AWS VPC, AWS IAM and IaC on AWS.

Am I ready? Stage 2 quiz

You manage five buckets with count over a list and remove the second name. What does the plan show?

  1. Only the second bucket is destroyed
  2. Nothing, count ignores removals
  3. The later buckets shift index, so several are replaced
  4. An error

With count, identity is the index. Use for_each with names as keys and only the removed one is destroyed.

You renamed aws_instance.web to aws_instance.app in your code. How do you avoid Terraform destroying and recreating it?

  1. Add a moved block from the old address to the new one
  2. Add depends_on
  3. Run terraform refresh
  4. Add ignore_changes = all

A moved block tells Terraform the object is the same, just at a new address. terraform state mv does it too, but outside code review.

How do you enable native state locking with the S3 backend in current Terraform?

  1. Create a DynamoDB table and set dynamodb_table
  2. Locking is impossible with S3
  3. Set lock = "s3" on the provider
  4. Set use_lockfile = true in the backend block

S3-native locking is generally available since Terraform 1.11; the DynamoDB arguments are deprecated in Terraform.

Which statement about the state file is true?

  1. It's safe to commit because it only holds IDs
  2. It can contain secrets in plain text, so store it in an encrypted, access-controlled backend
  3. Terraform regenerates it from the cloud if you delete it
  4. You should edit it by hand to fix problems

Attributes such as generated passwords end up in state. Protect it like a secret, and use the state commands or moved/import/removed blocks instead of editing it.

A Lambda function must not be created until an IAM policy is attached, but the code never references that policy. What do you add?

  1. A count on the policy
  2. A lifecycle block
  3. depends_on = [aws_iam_role_policy.lambda] on the function
  4. Nothing, Terraform creates resources in file order

Hidden dependencies need depends_on. Terraform ignores file order and creates independent resources in parallel.

Stage 3 · Intermediate Modules, environments and quality

Make your code reusable, run several environments from it, keep secrets out of it, and catch mistakes before they reach a plan. This is what separates a working configuration from one a team can maintain.

Modules: writing, using and versioning

Every folder of .tf files is a module; the one you run commands in is the root module. Call another module with a module block: module "vpc" { source = "./modules/vpc", cidr = "10.0.0.0/16" }. A module's variables are its inputs, its outputs are the only values the caller can see (module.vpc.subnet_ids), and variables don't leak in or out: each module has its own scope.

Sources can be a local path, a Git URL (git::https://…?ref=v1.2.0), or the public or a private registry (terraform-aws-modules/vpc/aws with version = "~> 6.0"). Always pin versions of shared modules and release them with semantic version tags. Good modules are small and focused, have a README, sensible defaults and validated inputs, and don't configure providers themselves. Read a popular registry module before writing your own: you'll learn a lot from how it's built, and you may not need to write one at all.

What to learn

  • Root vs child modules, and the standard module structure
  • Module inputs, outputs and variable scope
  • Module sources: local paths, Git with ?ref=, the registry with version
  • Versioning and releasing modules with semantic version tags
  • Using count / for_each on modules, and passing providers into them
  • Documenting a module (terraform-docs) and when not to wrap a single resource

Free resources

Practice

Move the network part of your AWS project (or the Docker containers) into a modules/ folder, call it twice with different inputs, and add moved blocks so nothing is recreated. Push the module to its own Git repository, tag v1.0.0 and call it with ?ref=v1.0.0. Compare your module with terraform-aws-modules/vpc.

Environments: workspaces vs directories

Most teams run dev, staging and production from the same code. There are two common ways. CLI workspaces (terraform workspace new staging) keep several state files for one configuration and backend, and code can branch on terraform.workspace. It's quick, but every environment shares the same backend and credentials, and it's easy to apply in the wrong one, so HashiCorp's own docs say workspaces aren't suitable for strong separation between environments.

The more common production layout is one directory per environment (envs/dev, envs/prod), each a small root module that calls shared modules with its own .tfvars, backend key and often its own AWS account. Changes are promoted by bumping a module version in dev first, then prod. Note that HCP Terraform workspaces are a different thing: each is a separate unit with its own state, variables and permissions.

What to learn

  • terraform workspace new / select / list / show and terraform.workspace
  • Where the S3 backend stores workspace state (workspace_key_prefix)
  • A directory-per-environment layout with shared modules and per-env tfvars and backend config
  • Separating environments by account and credentials, not just by state file
  • CLI workspaces vs HCP Terraform workspaces

Free resources

Practice

Run your Docker project in two workspaces and see the separate state files. Then restructure it into envs/dev and envs/prod folders that call the same module with different tfvars, and decide which layout you'd want to debug at 3 a.m.

Secrets and sensitive data

Never put secrets in .tf files or committed .tfvars. Pass them through environment variables (TF_VAR_db_password), read them at plan time from a secret store with a data source (AWS Secrets Manager, SSM Parameter Store, HashiCorp Vault), or better, let the service generate and keep them, such as RDS's manage_master_user_password. Mark variables and outputs sensitive = true so they're hidden in plan output, but remember that sensitive values are still stored in state.

Newer Terraform versions go further: ephemeral variables, outputs and resources (Terraform 1.10) are never written to plan or state, and write-only arguments (Terraform 1.11) let you send a value such as a password to a provider without it being saved. Whatever you do, protect the state backend (encryption, tight IAM, versioning) and give CI short-lived credentials instead of stored keys.

What to learn

  • Why secrets in code or committed tfvars are leaked secrets
  • sensitive = true and what it does and doesn't protect
  • Reading secrets from Secrets Manager, SSM or Vault with data sources
  • Ephemeral values and write-only arguments
  • Securing state: encryption, access control, versioning

Free resources

Practice

Add a random_password resource and a sensitive output for it. Look at the plan, then find the password in plain text in the state file with terraform show -json. Pass a second secret with TF_VAR_ instead of a file. The DevOps secrets topic covers secret stores in general.

Validation, custom conditions, checks and terraform test

Terraform has several layers of built-in checking. Variable validation blocks reject bad inputs. Preconditions and postconditions inside a resource's lifecycle block assert assumptions, for example "the AMI must be x86_64" or "the bucket must have versioning". check blocks (Terraform 1.5+) run assertions after every plan and apply, such as "the website returns HTTP 200", and only warn instead of failing.

terraform test (generally available since Terraform 1.6) runs .tftest.hcl files. Each run block does a plan or apply against real or mocked providers and checks assert conditions, then tears down what it created. Plan-only tests with mocked providers are free and fast, so they suit every pull request; apply tests against a sandbox account suit nightly runs.

What to learn

  • Variable validation with clear error messages
  • precondition and postcondition in lifecycle
  • check blocks with scoped data sources
  • terraform test: run blocks, command = plan, assert, expect_failures
  • Mock providers and overrides for fast, free tests

Free resources

Practice

Write a .tftest.hcl file for your module with two plan-only run blocks: one that checks a resource name is built correctly, and one that uses expect_failures to prove a bad input is rejected. Add a check block that warns if your Docker container's URL doesn't respond.

Linting and security scanning: tflint, checkov and trivy

terraform validate only checks that code is valid. TFLint goes further: unused variables, deprecated syntax, naming rules, and with its AWS ruleset, mistakes like an EC2 instance type that doesn't exist. Security scanners such as Checkov and Trivy (which absorbed tfsec) look for misconfigurations: public S3 buckets, security groups open to 0.0.0.0/0, unencrypted volumes, missing logging.

Run them in three places: in your editor, as pre-commit hooks (the pre-commit-terraform collection bundles fmt, validate, tflint, docs and scanners), and in CI on every pull request, where a failure blocks the merge. Scanners also work on plan JSON (terraform show -json tfplan), which sees values computed from variables. Suppress a finding only with a comment explaining why.

What to learn

  • terraform fmt -check and validate as the first CI gate
  • TFLint with a provider ruleset and a .tflint.hcl config
  • Checkov or Trivy for misconfiguration scanning, and reading their findings
  • pre-commit hooks for Terraform
  • Suppressing a false positive responsibly

Free resources

Practice

Run TFLint and Checkov (or Trivy) on your AWS project. Fix every high-severity finding, or write down why you accept it. Then add a pre-commit configuration so fmt and tflint run before every commit. The DevSecOps topic puts this in context.

Terraform with Kubernetes and Helm

Terraform can create a managed Kubernetes cluster (EKS, GKE, AKS) and, with the kubernetes and helm providers, install things into it. A common split: Terraform builds the cluster and the cloud resources around it (networking, IAM roles for workloads, databases), and a GitOps tool such as Argo CD or Flux deploys the applications. Managing the cluster and its contents in the same configuration is fragile, because the providers need the cluster's endpoint before it exists; keep them in separate configurations.

What to learn

  • Provisioning a managed cluster with a registry module
  • Configuring the kubernetes and helm providers from cluster outputs
  • Why the cluster and its workloads belong in separate root modules
  • Where Terraform stops and GitOps starts

Free resources

Practice

Free: create a local kind cluster, point the kubernetes provider at your kubeconfig, and create a namespace and a Helm release with Terraform. EKS costs money per hour, so if you try the EKS tutorial, destroy it straight away. See managed Kubernetes, Helm and GitOps.

Am I ready? Stage 3 quiz

How does a root module read a value created inside a child module?

  1. Through var. because variables are global
  2. The child module must declare an output, read as module.NAME.OUTPUT
  3. With a data block
  4. It can't

Modules are isolated: inputs come in through variables and only outputs are visible to the caller.

You mark a variable sensitive = true. What does that guarantee?

  1. The value is encrypted in state
  2. The value is never stored in state
  3. The value is sent to Vault
  4. The value is hidden in plan and apply output, but still stored in state

sensitive only redacts output. To keep a value out of state, use ephemeral values or write-only arguments, and always protect the backend.

Which is the best way to pin a shared Git module so updates don't surprise you?

  1. source = "git::https://…/vpc.git?ref=v1.4.0"
  2. source = "git::https://…/vpc.git"
  3. Copy the module into every project
  4. version = "latest"

A tag in ?ref= pins the exact release. The version argument only works for registry sources.

What does a check block do when its assertion fails?

  1. Stops the apply and rolls back
  2. Deletes the failing resource
  3. Reports a warning but doesn't block the run
  4. Nothing until you run terraform test

Check blocks are for ongoing health checks, so they warn instead of failing. Use preconditions/postconditions when a failure must stop the run.

Which tool would flag an S3 bucket that allows public access?

  1. terraform fmt
  2. A security scanner such as Checkov or Trivy
  3. terraform validate
  4. terraform graph

fmt and validate only check formatting and syntax. Misconfiguration scanners know the security rules for each resource type.

Stage 4 · Advanced Terraform in production

Run Terraform through pipelines instead of laptops, keep real infrastructure and code in sync, know the tooling landscape (HCP Terraform, OpenTofu, Terragrunt) and get ready for the Terraform Associate exam.

CI/CD for Terraform: plan on pull request, apply on merge

In a team, nobody should run apply from a laptop. The standard pipeline: on every pull request, CI runs fmt -check, validate, linters, tests and terraform plan, and posts the plan as a PR comment for reviewers. When the PR is merged, CI applies the reviewed change, ideally the saved plan file from the same commit, and production applies wait for a manual approval through a protected environment.

Credentials matter most. Don't store long-lived AWS keys as CI secrets: with OpenID Connect (OIDC), GitHub Actions gets a short-lived token that AWS trusts to assume an IAM role, limited to your repository and branch. Give the plan job a read-only role and only the apply job write access. Run with -input=false and pin the Terraform version with hashicorp/setup-terraform (or opentofu/setup-opentofu).

What to learn

  • A PR workflow: fmt, validate, lint, test, plan, plan as a comment
  • Apply on merge with the reviewed plan, and approval gates for production
  • OIDC from GitHub Actions to an AWS IAM role (no stored keys)
  • Separate read-only plan and write apply roles
  • Concurrency: one run per state at a time, and handling locks in CI

Free resources

Practice

Put your project in a GitHub repository. Add a workflow that runs fmt, validate and plan on pull requests (start with a plan-only job against the local/random providers, which needs no cloud), then add an OIDC role and an apply job on merge to main behind a protected environment. Remember to destroy afterwards. Related: GitHub Actions, pull requests and CI/CD.

HCP Terraform (formerly Terraform Cloud)

HCP Terraform is HashiCorp's hosted service for running Terraform. It stores state with locking, runs plans and applies remotely, triggers runs from Git (VCS-driven workflow), and adds team permissions, a private module registry, variable sets, policy checks, health assessments and dynamic provider credentials (OIDC to the cloud). You connect a configuration with a cloud {} block and terraform login. Terraform Enterprise is the self-hosted edition.

Work is organised into organisations, projects and workspaces (one state and its settings per workspace). The Free plan covers most features for up to 500 managed resources with one concurrent run (checked 22 October 2026); the exam expects you to know which features exist and how workspaces and projects are organised.

What to learn

  • The cloud block, terraform login and migrating local state
  • CLI-driven vs VCS-driven vs API-driven runs
  • Organisations, projects, workspaces, variable sets and teams
  • Private registry, policy enforcement (Sentinel/OPA) and run tasks
  • Dynamic provider credentials and health assessments

Free resources

Practice

Sign up for the Free plan, migrate your random/local or Docker project's state with a cloud block, and run a plan remotely. Then connect a GitHub repository so a pull request triggers a speculative plan.

Drift detection and day-2 operations

Drift is when real infrastructure no longer matches the code, usually because someone changed it in the console. terraform plan shows drift as changes it wants to undo. terraform plan -refresh-only shows only what changed outside Terraform, and apply -refresh-only accepts those changes into state without touching infrastructure. Then decide: update the code to match, or apply to put things back.

Catch drift early with a scheduled plan in CI (fail or alert if the plan isn't empty, using plan -detailed-exitcode, which exits with 2 when there are changes) or HCP Terraform's health assessments. Prevent it with read-only console access for humans. Upgrading Terraform and providers regularly is the other day-2 job: read the upgrade guide and changelog, bump one thing at a time, and check that the plan is empty.

What to learn

  • What drift is and how it appears in a plan
  • plan -refresh-only and apply -refresh-only
  • Scheduled drift detection with plan -detailed-exitcode
  • When ignore_changes is the right answer (autoscaling counts, tags set by other tools)
  • Upgrading Terraform and providers safely

Free resources

Practice

Change your Docker container (or a tag on an AWS resource) by hand, then run a normal plan and a -refresh-only plan and compare them. Add a nightly scheduled workflow that runs plan -detailed-exitcode and fails on drift.

Troubleshooting and debug logging

Most Terraform errors fall into four groups: syntax and validation errors (fix the code; validate catches them), provider and API errors (permissions, quotas, invalid values; read the API message inside the error), state problems (a stale lock, a resource deleted outside Terraform, an address mismatch after refactoring) and dependency problems (cycles, values unknown until apply used in count or for_each).

When the message isn't enough, turn on logs: TF_LOG=DEBUG (levels TRACE, DEBUG, INFO, WARN, ERROR), TF_LOG_PATH to write them to a file, and TF_LOG_CORE / TF_LOG_PROVIDER to separate Terraform's own logs from the provider's. Logs can include secrets, so don't paste them publicly.

What to learn

  • Recognising language, provider, state and dependency errors
  • TF_LOG, TF_LOG_PATH, TF_LOG_CORE and TF_LOG_PROVIDER
  • Clearing a stale lock with force-unlock, safely
  • Fixing "value depends on resource attributes that cannot be determined until apply"

Free resources

Practice

Run a plan with TF_LOG=DEBUG TF_LOG_PATH=tf.log and find the HTTP request your provider sent. Then break your Docker project three ways (a typo, an invalid port, a container deleted by hand) and fix each from the error message alone.

OpenTofu and the licence change

In August 2023 HashiCorp moved Terraform from the open-source MPL 2.0 licence to the Business Source License (BUSL 1.1), which restricts using it in products that compete with HashiCorp. In response, a group of companies forked the last MPL version as OpenTofu, now a Linux Foundation project that stays under MPL 2.0. The CLI is tofu, it reads the same HCL, works with the same providers and state, and has its own registry.

The two have since grown apart a little. OpenTofu added features of its own, such as built-in state and plan encryption, while Terraform added others, so check the docs before relying on a feature that only one has. For learning, nearly everything on this page works in both. Pick based on licence needs, the features you want and whether you use HCP Terraform (Terraform only). Migration is mostly installing tofu and running tofu init; follow the official guide and back up state first.

What to learn

  • The licence change: MPL 2.0 to BUSL 1.1, and why OpenTofu was forked
  • What is the same (HCL, providers, state format) and what differs
  • OpenTofu-only features such as state encryption
  • Migrating a project from Terraform to OpenTofu, and back

Free resources

Practice

Install OpenTofu, copy your Docker project, run tofu init and tofu plan against the existing state and check the plan is empty. Then turn on state encryption with a passphrase key provider and look at the encrypted state file.

Large-scale layout: many accounts, many states

One giant state for everything means slow plans, a huge blast radius and everyone waiting on one lock. Larger setups split state by environment (often one AWS account each), by region and by component or lifecycle (network, data, compute, applications), so a change to an app can't touch the VPC. Shared values flow between them through outputs read as data sources or parameters.

On AWS this goes with a multi-account setup through AWS Organizations: a dedicated account for state and CI, workload accounts per environment, and Terraform assuming a role into each account. Keep modules in a versioned catalogue and root modules thin.

What to learn

  • Splitting state by environment, region and component, and blast radius
  • Passing values between states without tight coupling
  • Assuming roles into several AWS accounts from one pipeline
  • Monorepo vs a repository per module, and module catalogues

Free resources

Practice

On paper, split your AWS project into separate states (network, app) and list exactly which outputs each one needs from the other. If you have an AWS Organization, deploy the network into a second account by assuming a role. See AWS multi-account.

Terragrunt

Terragrunt is an open-source wrapper around Terraform and OpenTofu for codebases with many small root modules. It generates repeated backend and provider blocks from one place, passes outputs between units through declared dependencies, and runs commands across many units in dependency order. It solves real repetition at scale, but adds another tool to learn, so start with plain Terraform and reach for it when the duplication hurts.

What to learn

  • The problem: repeated backend/provider config across many root modules
  • Units, include, and generated backend configuration
  • Dependencies between units and running across a whole stack
  • When plain Terraform (or HCP Terraform Stacks) is enough

Free resources

Practice

Convert your envs/dev and envs/prod layout to Terragrunt with one shared root configuration for the backend, using the local or Docker providers so it costs nothing. Compare the line counts before and after.

Policy as code: OPA, Conftest and Sentinel

Scanners check generic best practice; policy as code enforces your organisation's own rules on every plan: "only these instance types", "every resource has a cost-centre tag", "no public buckets in production". Open Policy Agent (with Conftest) evaluates policies written in Rego against plan JSON in any CI system. HCP Terraform runs Sentinel or OPA policies between plan and apply and can block a run.

What to learn

  • Exporting a plan as JSON with terraform show -json
  • Writing a small Rego policy and testing it with Conftest
  • Advisory vs mandatory policies
  • Policy enforcement in HCP Terraform

Free resources

Practice

Write a Conftest policy that fails when any resource in your plan JSON lacks an owner tag, and add it to your PR workflow.

Terraform Associate exam prep

The HashiCorp Certified: Terraform Associate (004) exam checks foundational knowledge: IaC concepts, providers, the core workflow, configuration (resources, data, variables, outputs, complex types, expressions, functions, dependencies, custom conditions, sensitive data), modules, state and backends, import and state inspection, verbose logging, and HCP Terraform features. It's multiple choice, so hands-on practice from this roadmap plus a careful read of the official exam content list is the best preparation.

Go through the official study guide and content list objective by objective, and tick off each one only when you could explain it to someone. Try the official sample questions, and redo every stage quiz on this page. Watch out for questions about what the Community edition vs HCP Terraform offers, and the exact behaviour of commands such as init -upgrade, -refresh-only, -replace and state rm.

What to learn

  • Read the exam objectives and map each to a topic on this page
  • Work through the official study guide and exam content list
  • Answer the official sample questions
  • Review command flags and HCP Terraform features you haven't used
  • Book the exam and check the system requirements for online proctoring

Free resources

Practice

Score 5/5 on every stage quiz here, then answer all the official sample questions without notes. For any objective you can't explain, redo the matching practice task with the local, random or Docker providers.

Am I ready? Stage 4 quiz

What is the safest way to give a GitHub Actions workflow access to AWS for Terraform?

  1. Store an IAM user's access keys as repository secrets
  2. Commit the keys in an encrypted tfvars file
  3. Use OIDC so the workflow assumes an IAM role with short-lived credentials
  4. Give the runner an administrator account

OIDC means there are no long-lived keys to leak, and the role's trust policy can be limited to your repository and branch.

Someone changed a security group in the console. Which command shows only what changed outside Terraform, without proposing to change infrastructure?

  1. terraform plan -refresh-only
  2. terraform apply -auto-approve
  3. terraform validate
  4. terraform state rm

Refresh-only mode compares state with reality. Applying it updates state to match; it never changes the real resources.

Which statement about OpenTofu is correct?

  1. It's a paid edition of Terraform
  2. It uses a different configuration language
  3. It was created by HashiCorp to replace Terraform
  4. It's an MPL 2.0 fork of Terraform under the Linux Foundation, created after Terraform moved to the BUSL

OpenTofu forked from the last MPL-licensed Terraform in 2023 and reads the same HCL.

How do you get detailed debug logs from Terraform written to a file?

  1. terraform plan --verbose
  2. Set TF_LOG=DEBUG and TF_LOG_PATH=tf.log
  3. Run terraform graph
  4. Add debug = true to the provider block

TF_LOG sets the level and TF_LOG_PATH the file. Remember the logs may contain secrets.

In a typical Terraform pipeline, when does apply run?

  1. On every push to any branch
  2. Before the plan, to save time
  3. After the pull request with its plan has been reviewed and merged
  4. Only on a developer's laptop

Plan on the PR so reviewers see exactly what will change; apply after merge (with an approval for production).

How to use this roadmap

  • Start without a cloud account. Stages 1 to 3 work with the local, random and docker providers, or with LocalStack, so you can learn the whole language for free. Move to AWS for the stage 2 project.
  • Always destroy. When you practise on AWS, run terraform destroy the same day and set a budget alert. Being able to rebuild everything with one command is the point of IaC.
  • Read every plan. Most Terraform accidents happen when someone applies a plan they didn't read. Look for -/+ and - lines first.
  • Track your progress. Ticking the first item in a topic marks it as in progress; ticking them all marks it done. Progress stays in this browser. Use Export to move it to another device, or Share progress to send a link.
  • Use the filter. Core IaC is the path every Terraform user needs, Terraform Associate highlights the exam topics, and Teams & production covers running Terraform with others.
  • Optional topics (dashed borders) are useful but not needed to finish, and don't count towards the percentage.
  • Next steps: Terraform is one part of the DevOps roadmap. Pair it with the AWS roadmap for the cloud services you'll be describing, the Git & GitHub roadmap for the pull request workflow, Ansible for configuring servers, and the Kubernetes roadmap for what usually runs on top.

The Terraform Associate exam

The HashiCorp Certified: Terraform Associate (004) is a multiple-choice exam taken online with a proctor. It lasts 1 hour, tests Terraform 1.12, is in English, and the credential expires after 2 years. The price on the exam page is US$70.50 plus local taxes and fees, with no free retake. Prices and details change, so check the exam page before booking. Topics tagged Terraform Associate above follow its eight objective areas. After the Associate, HashiCorp also offers Terraform Authoring and Operations Advanced and Terraform Infrastructure Engineer Professional certifications.

Versions when this page was checked: Terraform 1.17.0 (released 21 October 2026) and OpenTofu 1.13.2. The exam still targets Terraform 1.12, so a few newer features won't be on it. (All facts checked on 22 October 2026.)

Terraform cheat sheet

Startterraform init · terraform init -upgrade · terraform init -migrate-state
Checkterraform fmt -recursive · terraform validate · terraform test
Plan & applyterraform plan -out=tfplan · terraform apply tfplan · terraform apply -replace=ADDR · terraform destroy
Variables-var-file=prod.tfvars · -var 'env=prod' · TF_VAR_env=prod · terraform output -json
Stateterraform state list · state show ADDR · state mv · state rm · plan -refresh-only · force-unlock ID
Workspacesterraform workspace list · workspace new NAME · workspace select NAME
Explore & debugterraform console · terraform graph · terraform show -json tfplan · TF_LOG=DEBUG TF_LOG_PATH=tf.log