Cloud and DevOps
Terraform
How Terraform turns files into infrastructure: the write, plan, apply loop, the state file that makes it work, and the habits that stop a rename from deleting a database, told mostly in diagrams around a small bank API on AWS. Nothing on this page was run: Terraform was not installed and no cloud account was used, so every command is unrun and every output block is typical output, shortened and written to show the format.
The idea
Part 1 of 5 · why, the loop, and the three things Terraform compares
Why infrastructure as code
Infrastructure as code means the servers, networks and databases are described in files that are reviewed, versioned and applied by a tool. Terraform is declarative: the files say what should exist, and the tool works out the steps.
| Console clicks | Shell scripts | Terraform | |
|---|---|---|---|
| Says | Nothing, it is in someone's head | How: a list of steps | What: the end result |
| Run twice | Human error | Fails or duplicates unless written with care | No changes the second time |
| Review | None | Code review of steps | Code review plus a plan of exact changes |
| Second environment | Click it all again | Copy and edit | Same code, different variables |
Limit: Terraform creates and wires infrastructure. It is a poor fit for installing software inside a server or for deploying application releases many times a day.
The core loop
The idea · Not run for this page.
Four steps, repeated for every change. plan only reads, apply is the only step that changes real infrastructure.
init is needed again only when providers, modules or the backend change.| Command | Does | Touches the cloud? |
|---|---|---|
terraform init | Downloads providers and modules, connects the backend | No (only the state backend) |
terraform fmt, validate | Formats files, checks syntax and types | No |
terraform plan | Reads real resources, prints the difference | Read only |
terraform apply | Plans, asks for yes, makes the changes, writes state | Yes |
terraform destroy | Deletes everything in the state | Yes |
Config, state, real world
Terraform keeps three pictures of the same infrastructure in agreement. Almost every Terraform problem is two of them disagreeing.
The running example
The bank API needs a network, a server, a PostgreSQL database, a queue for transfers and a bucket for statements. Every block on this page is a piece of that, written for the AWS provider.
File names are a convention. Terraform reads every .tf file in the directory as one configuration, in no particular order.
Writing configuration
Part 2 of 5 · the building blocks of HCL
Providers and version pinning
Writing configuration · Not run for this page.
Terraform itself knows nothing about AWS. A provider is a plugin that maps resource blocks to API calls, and both the tool and each provider are pinned to a version range.
| Constraint | Allows | Use for |
|---|---|---|
= 6.4.0 | Exactly that version | Rarely: the lock file already does this |
>= 1.11 | That version or anything newer | required_version, reusable modules |
~> 6.0 | 6.0 up to, not including, 7.0 | Providers in a root configuration |
~> 6.4.0 | 6.4.0 up to, not including, 6.5.0 | Patch releases only |
Approximate: the version numbers here are examples. Check the docs for the current Terraform and AWS provider releases before copying them.
The lock file
Writing configuration · Not run for this page.
The constraint says which versions are allowed. .terraform.lock.hcl records the one version that was chosen, with checksums, so every laptop and every CI run uses the same provider.
init -upgrade moves a locked provider to a newer version.- Commit
.terraform.lock.hcl. Ignore.terraform/,*.tfstateand any tfvars file holding secrets. - Trap: a lock file written on a Mac may lack checksums for Linux, and CI then fails at
init.terraform providers lock -platform=linux_amd64 -platform=darwin_arm64records both.
Resources and data sources
Writing configuration · Not run for this page.
A resource block is something Terraform creates and owns. A data block only looks something up. Both are addressed as type.name.attribute, with a data. prefix for data sources.
| resource | data | |
|---|---|---|
| Terraform | Creates, updates, deletes | Reads only |
On destroy | Deleted | Untouched |
| Typical use | Everything this config owns | An image id, the zones of a region, a network another team owns |
Trap: most_recent = true means a new image release shows up as a server replacement in the next plan. Pin the image id where surprise replacements are not acceptable.
Variables, locals, outputs
Writing configuration · Not run for this page.
Think of a configuration as a function: variables are its parameters, locals are its local names, outputs are its return values.
| Where a variable value comes from | Priority |
|---|---|
default in the variable block | Lowest |
Environment variable TF_VAR_env | |
terraform.tfvars | |
*.auto.tfvars | |
-var and -var-file on the command line | Highest |
A variable with no default and no value makes Terraform prompt for it, and fail in CI where -input=false is set. sensitive = true on a variable or output hides it in the terminal and nowhere else.
The dependency graph
Writing aws_vpc.bank.id inside the subnet is a dependency. Terraform builds a graph from these references, creates in that order, destroys in reverse, and runs independent branches in parallel (10 at a time by default).
| Implicit | Explicit: depends_on | |
|---|---|---|
| Written as | A reference to another resource's attribute | depends_on = [aws_iam_role_policy.api] |
| Use when | Always, if a value is passed | Order matters but no value is passed, for example a server that needs a permission to exist before it boots |
| Cost | None | Hides the reason, and makes plans more conservative: more "known after apply" |
terraform graph prints the graph in DOT format. A cycle is an error at plan time, not a hang.
count versus for_each
Writing configuration · Not run for this page.
Both make several copies of one block. count addresses copies by position, for_each by key, and position is the trap: remove an item from the middle of the list and everything after it shifts.
Now delete "statements" from the list.
count: index 1 now means "alerts", so the queue at 1 is replaced and the real alerts queue at 2 is destroyed, with its messages.for_each: only the removed key is destroyed.| Use | When |
|---|---|
count = var.enabled ? 1 : 0 | Zero or one of something |
count = 3 | Identical, interchangeable copies |
for_each over a set or map | Everything else: copies that have a name |
Limit: for_each keys must be known at plan time. Keys built from another resource's id fail with "Invalid for_each argument".
Plan and state
Part 3 of 5 · reading a plan, and the file everything depends on
Reading a plan
Plan and state · Not run for this page.
Read the last line first, then every - and -/+. The words "forces replacement" mark the argument that turned an edit into a delete and recreate.
| Symbol | Meaning | Risk |
|---|---|---|
+ | Create | Low |
~ | Update in place | Usually low; some updates restart the resource |
- | Destroy | High |
-/+ | Replace: destroy, then create | High: downtime, data in it is gone |
+/- | Replace: create, then destroy | Medium: see create_before_destroy |
<= | Read a data source during apply | None |
An unexpected destroy is usually a rename, an index shift or a force-replacement argument: stop and find the cause. terraform plan -out=tfplan saves the plan, and terraform apply tfplan applies exactly that and nothing newer. (known after apply) means the value does not exist until the resource does.
What state holds
State is a JSON file that maps each address in the config to one real resource id, with a copy of all its attributes. Without it Terraform cannot tell "create this" from "this already exists".
| Field | Why it is there |
|---|---|
| Address to id mapping | Knows which real queue aws_sqs_queue.transfers is |
| Attributes | Lets other resources and outputs read values without an API call; this is also where secrets leak |
| Dependencies | Destroy order for resources already deleted from the config |
serial | Goes up on every write; a backend rejects an older serial |
lineage | Identity of this state; stops one state overwriting another |
Never edit it by hand. A wrong id or a stale serial makes Terraform create duplicates or destroy the wrong thing. Change state only through moved, import and the state commands, and keep backend versioning on so there is a copy to go back to.
Remote backends and locking
Plan and state · Not run for this page.
By default state is a local file, which is lost with the laptop and cannot be shared. A backend stores it remotely and takes a lock so two applies cannot write at once.
-lock-timeout=5m.| Backend needs | Why |
|---|---|
| Locking | Two writers corrupt state |
| Versioning | Roll back after a bad write |
| Encryption at rest | State holds secrets |
| Tight access | Read access to state is read access to every secret in it |
| One state per environment | A mistake in dev cannot touch prod |
- Approximate:
use_lockfileis the S3 backend's own locking in recent Terraform releases. Older setups lock through a DynamoDB table (dynamodb_table). Check the docs for your version. - Backend blocks cannot use variables. Pass per-environment values with
terraform init -backend-config=prod.s3.tfbackend. - The state bucket is a chicken and egg resource: create it once by hand or from a tiny separate configuration.
Secrets in state
Plan and state · Not run for this page.
Every attribute of every resource is stored in state as plain text, passwords included. sensitive = true only replaces the value with (sensitive value) in terminal output.
| Option | Secret in state? |
|---|---|
password = var.db_password | Yes |
| Let the cloud generate and store it (above) | No, only a reference |
| Create the secret outside Terraform, pass only its name or ARN | No |
| Reading a secret with a data source | Yes: data source results are stored too |
| Write-only arguments and ephemeral values (newer releases, check the docs) | No |
The block refers to two more subnets and a second security group that are not shown. Whatever the option, treat the state bucket as a secret store: encrypted, versioned, readable by few. Never commit *.tfstate.
Drift
Plan and state · Not run for this page.
Drift is the real world changing behind Terraform's back: someone opens a port in the console during an incident. The next plan notices, and by default proposes to undo it.
plan -refresh-onlyshows what changed outside Terraform and proposes no infrastructure change.apply -refresh-onlywrites that into state.- Detect it: a scheduled CI job running
terraform plan -detailed-exitcode. Exit 0 is no changes, 2 is changes, 1 is an error. - Prevent it: read-only console access in production, changes only through the pipeline.
import, moved, state mv and rm
Plan and state · Not run for this page.
These change the mapping between addresses and real resources without touching the resources. Prefer the blocks: they are code, they are reviewed, and they show up in the plan.
| Command | Does |
|---|---|
terraform state list | Every address in state |
terraform state show ADDR | Attributes of one resource |
terraform state mv OLD NEW | Rename an address, the imperative form of moved |
terraform state rm ADDR | Forget a resource; it keeps running |
terraform import ADDR ID | The older, command form of the import block |
terraform state pull | Print the remote state, useful for a backup first |
Import needs matching config. After an import the plan must show no changes; if it shows a diff, the written block does not describe the real resource yet. terraform plan -generate-config-out=generated.tf writes a first draft. Block support depends on the Terraform version: check the docs.
Structure
Part 4 of 5 · reuse, environments and guard rails
Modules
Structure · Not run for this page.
A module is a directory of .tf files used as a unit: variables in, resources inside, outputs out. The directory you run terraform in is the root module.
| Source | Pin with |
|---|---|
Local path ../../modules/network | Nothing: it changes with the repo |
| Git URL | ?ref=v1.2.0, a tag or commit, never a branch |
Registry namespace/name/provider | The version argument |
Resources inside a module are addressed as module.queues.aws_sqs_queue.this["transfers"]. Run terraform init after adding a module or changing its source.
When to write a module
A module is an interface, and interfaces cost something to change. Write one when it hides a decision, not when it hides one resource.
| Write a module | Do not |
|---|---|
| The same group of resources is needed in two or more places | It wraps a single resource and passes every argument through |
| It encodes a rule: every queue gets a dead letter queue and an alarm | It is used once and nothing else is planned |
| Another team should use it without reading it | Its variables outnumber its resources by a wide margin |
- Inputs: few, typed, with validation. Defaults for the safe choice.
- Outputs: ids, ARNs and endpoints the caller needs. Nothing else.
- No provider configuration inside a shared module; only
required_providerswith a loose>=constraint. The root module configures providers. - Versioning: semantic versions as Git tags. A renamed resource inside the module ships with a
movedblock so callers do not see a destroy.
Environments
Structure · Not run for this page.
Dev, staging and prod need the same code, different sizes and separate state. There are three common ways to arrange that.
| Workspaces | One directory, tfvars per env | Directory per env | |
|---|---|---|---|
| How | terraform workspace select prod | -var-file=prod.tfvars plus -backend-config | cd envs/prod |
| State | One backend, one key per workspace | One key or backend per env | One backend config per env |
| Code can differ per env | Only through conditionals | Only through variables | Yes, including module versions |
| Main risk | Applying in the wrong workspace; shared credentials | Wrong var file with the wrong backend | Environments slowly diverge |
| Fits | Short-lived copies, per-branch previews | Small teams, identical environments | Production systems with separate accounts |
Inside a configuration, terraform.workspace gives the current workspace name. Also split state by layer (network, data, app) once one plan becomes slow or one mistake can reach everything.
Lifecycle rules
Structure · Not run for this page.
The lifecycle block inside a resource changes how Terraform treats that one resource.
| Rule | Effect | Trap |
|---|---|---|
prevent_destroy | Any plan that would destroy the resource fails | Deleting the whole block removes the rule with it, and the plan then destroys |
create_before_destroy | Replacement is created first | Fails when a unique name is fixed: both copies need it at once |
ignore_changes | Listed arguments are not corrected after creation | ignore_changes = all hides real drift |
replace_triggered_by | Replace this when another resource changes | Easy to cause surprise replacements |
Use ignore_changes for values another system owns, such as a count managed by an autoscaler. To force one replacement by hand, use terraform apply -replace=aws_instance.api.
Operating
Part 5 of 5 · the pipeline, what goes wrong, and the alternatives
Plan on pull request, apply on merge
Operating · Not run for this page. The workflow was never executed and was not checked with a linter.
People stop applying from laptops. The pull request shows the plan, a reviewer reads it next to the code, and only the pipeline holds credentials that can change production.
- Two roles: the plan role is read-only plus state access, the apply role can write and is usable only from
main. - Left out: posting the plan as a pull request comment (
terraform show -no-color tfplan), and the approver seeing the second plan before approving. A saved plan file contains secrets, so treat it like state if it is uploaded as an artifact.
Common failures
Operating · Not run for this page.
| Symptom | Cause | Fix |
|---|---|---|
| "Error acquiring the state lock" | Another run is active, or a run was killed before it released the lock | Confirm nobody is running, then terraform force-unlock LOCK_ID |
| Plan wants to change things nobody edited | Drift, or a provider that changed a default | Revert, adopt in code, or ignore_changes for values owned elsewhere |
| Plan destroys and creates after a refactor | Rename or index shift | moved block, for_each |
| Apply failed halfway | An API error, a quota, a timeout | Fix the cause and apply again: finished resources are already in state. There is no automatic rollback. |
| "already exists" on create | The resource exists but is not in state | import it |
| Large unexpected diff after an upgrade | New provider major version: renamed arguments, changed defaults | See below |
| CI fails at init with a checksum error | Lock file lacks the CI platform | terraform providers lock -platform=... |
Provider upgrade: read the upgrade guide, raise the constraint on a branch, run init -upgrade, and fix the config until the plan in dev is empty; then dev, staging, prod, with the new lock file in the same change. One way: a newer provider may rewrite its resources in state in a newer format on apply, and the old provider cannot read that. Upgrade one major version at a time, and rely on backend versioning as the way back.
Destroy by rename
Operating · Not run for this page.
The address is the identity. Rename aws_db_instance.bank to aws_db_instance.primary, or move it into a module, and Terraform sees one resource removed and a different one added.
moved block.| Edit that changes an address | Guard |
|---|---|
| Renaming a resource or module label | moved |
| Moving a resource into or out of a module | moved |
Switching count to for_each | moved from x[0] to x["key"] |
| Anything on a database or bucket | prevent_destroy, deletion protection on the resource itself, backups |
Terraform and its alternatives
All four keep a record of what they created and compute a difference. They differ in language, in who holds the state and in licence. Details change: treat this table as approximate and check the docs.
| Terraform | OpenTofu | Pulumi | CloudFormation | |
|---|---|---|---|---|
| Language | HCL | HCL, same files | Python, Go, TypeScript and others | YAML or JSON |
| Clouds | Many, through providers | Many, same provider ecosystem | Many, a lot through Terraform providers | AWS only |
| State | You manage a backend, or use the vendor's service | Same, plus built-in state encryption | Vendor service by default, or your own bucket | Held by AWS, nothing to manage |
| Preview | plan | plan | preview | Change sets |
| On a failed apply | Stops, partial result stays | Same | Stops, partial result stays | Rolls the stack back |
| Licence | Source available (BSL) since 2023 | Open source (MPL), a fork under the Linux Foundation | Open source engine | Proprietary service |
| Choose when | The default; the most examples and hiring pool | An open licence matters, or you want its extra features | Infrastructure needs real loops, types and tests | AWS only, and you want no state to run |
Interview line: the concepts on this page (declared config, state, plan, drift, import) carry across all four. Only the syntax and the state owner change.
Cheat sheet
Operating · Not run for this page.
| I want to | Command or block |
|---|---|
| Set up a fresh checkout | terraform init |
| Move providers to newer versions | terraform init -upgrade |
| Format and check | terraform fmt -recursive, terraform validate |
| See what would change | terraform plan -var-file=prod.tfvars |
| Apply exactly what was reviewed | terraform plan -out=tfplan, then terraform apply tfplan |
| Read a saved plan | terraform show tfplan |
| Look for drift only | terraform plan -refresh-only |
| Recreate one resource | terraform apply -replace=ADDR |
| Work on one resource (emergencies) | terraform plan -target=ADDR |
| List or inspect what is managed | terraform state list, terraform state show ADDR |
| Rename without destroying | moved { from = ... to = ... } |
| Adopt an existing resource | import { to = ... id = "..." } |
| Forget a resource, keep it running | removed block or terraform state rm ADDR |
| Clear a stuck lock | terraform force-unlock LOCK_ID |
| Switch workspace | terraform workspace select NAME |
| Tear everything down | terraform destroy |
Interview questions
| Question | Short answer |
|---|---|
| Why does Terraform need state? | To map config addresses to real ids, so it can tell create from update and can delete what was removed from the config. See state. |
| What happens when two people apply at once? | With a locking backend the second fails or waits. Without one, the later write wins and state no longer matches reality. See locking. |
| Someone changed a resource in the console. Then what? | The next plan shows the drift and proposes to revert it. Revert, adopt it in code, or record it with -refresh-only. See drift. |
count or for_each? | for_each for named things, because removing a middle item from a count list shifts every later index. count for zero-or-one. See the trap. |
| How do you rename a resource safely? | A moved block, and a plan that shows no destroy. See destroy by rename. |
| How do you bring existing infrastructure under Terraform? | Write the block, add an import block, and iterate until the plan shows no changes. See import. |
Does sensitive = true protect a secret? | Only on screen. It is in state as plain text, so keep secrets out of state or lock the state down. See secrets. |
| How do you separate dev and prod? | Separate state and, ideally, separate accounts and credentials: a directory per environment calling shared modules. Workspaces for short-lived copies. See environments. |
What does ~> 6.0 mean, and what is the lock file for? | Any 6.x. The lock file records the exact version and checksums so every run uses the same one. See the lock file. |
| An apply failed halfway. What state are you in? | Completed resources are real and recorded. Fix and apply again; there is no rollback. See failures. |
| How do you stop a production database being deleted? | Layers: prevent_destroy, deletion protection on the database, reviewed plans, an apply role only CI can use, backups. See lifecycle. |
When is depends_on right? | Only when order matters and no attribute is referenced. Otherwise a reference already creates the edge. See the graph. |
Back to Cloud and DevOps.