Learnings

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

The idea

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 clicksShell scriptsTerraform
SaysNothing, it is in someone's headHow: a list of stepsWhat: the end result
Run twiceHuman errorFails or duplicates unless written with careNo changes the second time
ReviewNoneCode review of stepsCode review plus a plan of exact changes
Second environmentClick it all againCopy and editSame 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.

Write, init, plan, apply. init is needed again only when providers, modules or the backend change.
CommandDoesTouches the cloud?
terraform initDownloads providers and modules, connects the backendNo (only the state backend)
terraform fmt, validateFormats files, checks syntax and typesNo
terraform planReads real resources, prints the differenceRead only
terraform applyPlans, asks for yes, makes the changes, writes stateYes
terraform destroyDeletes everything in the stateYes

Config, state, real world

The idea

Terraform keeps three pictures of the same infrastructure in agreement. Almost every Terraform problem is two of them disagreeing.

Config is what you want, state is what Terraform believes it made, the real world is what exists.
DisagreementNamePlan shows
In config, not in stateNew resource+ create
In state, not in configRemoved resource- destroy
Real world differs from stateDrift~ change it back
Exists for real, not in stateUnmanagedNothing, until an import

The running example

The idea

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.

Eight boxes, about ten resources. Arrows point from what must exist first.

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.

ConstraintAllowsUse for
= 6.4.0Exactly that versionRarely: the lock file already does this
>= 1.11That version or anything newerrequired_version, reusable modules
~> 6.06.0 up to, not including, 7.0Providers in a root configuration
~> 6.4.06.4.0 up to, not including, 6.5.0Patch 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.

Only init -upgrade moves a locked provider to a newer version.
  • Commit .terraform.lock.hcl. Ignore .terraform/, *.tfstate and 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_arm64 records 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.

resourcedata
TerraformCreates, updates, deletesReads only
On destroyDeletedUntouched
Typical useEverything this config ownsAn 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 fromPriority
default in the variable blockLowest
Environment variable TF_VAR_env
terraform.tfvars
*.auto.tfvars
-var and -var-file on the command lineHighest

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 configuration

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).

The queue and bucket depend on nothing, so they are created at the same time as the VPC.
ImplicitExplicit: depends_on
Written asA reference to another resource's attributedepends_on = [aws_iam_role_policy.api]
Use whenAlways, if a value is passedOrder matters but no value is passed, for example a server that needs a permission to exist before it boots
CostNoneHides 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.
UseWhen
count = var.enabled ? 1 : 0Zero or one of something
count = 3Identical, interchangeable copies
for_each over a set or mapEverything 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.

SymbolMeaningRisk
+CreateLow
~Update in placeUsually low; some updates restart the resource
-DestroyHigh
-/+Replace: destroy, then createHigh: downtime, data in it is gone
+/-Replace: create, then destroyMedium: see create_before_destroy
<=Read a data source during applyNone

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

Plan and state

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".

FieldWhy it is there
Address to id mappingKnows which real queue aws_sqs_queue.transfers is
AttributesLets other resources and outputs read values without an API call; this is also where secrets leak
DependenciesDestroy order for resources already deleted from the config
serialGoes up on every write; a backend rejects an older serial
lineageIdentity 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.

The second run fails fast, or waits with -lock-timeout=5m.
Backend needsWhy
LockingTwo writers corrupt state
VersioningRoll back after a bad write
Encryption at restState holds secrets
Tight accessRead access to state is read access to every secret in it
One state per environmentA mistake in dev cannot touch prod
  • Approximate: use_lockfile is 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.

OptionSecret in state?
password = var.db_passwordYes
Let the cloud generate and store it (above)No, only a reference
Create the secret outside Terraform, pass only its name or ARNNo
Reading a secret with a data sourceYes: 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.

Three answers to drift: revert it, adopt it in code, or just update state.
  • plan -refresh-only shows what changed outside Terraform and proposes no infrastructure change. apply -refresh-only writes 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.

Pick by what disagrees: the real world, the name, or the ownership.
CommandDoes
terraform state listEvery address in state
terraform state show ADDRAttributes of one resource
terraform state mv OLD NEWRename an address, the imperative form of moved
terraform state rm ADDRForget a resource; it keeps running
terraform import ADDR IDThe older, command form of the import block
terraform state pullPrint 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.

Modules never reach into each other. The root passes one module's outputs to the next module's inputs.
SourcePin with
Local path ../../modules/networkNothing: it changes with the repo
Git URL?ref=v1.2.0, a tag or commit, never a branch
Registry namespace/name/providerThe 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

Structure

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 moduleDo not
The same group of resources is needed in two or more placesIt wraps a single resource and passes every argument through
It encodes a rule: every queue gets a dead letter queue and an alarmIt is used once and nothing else is planned
Another team should use it without reading itIts 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_providers with a loose >= constraint. The root module configures providers.
  • Versioning: semantic versions as Git tags. A renamed resource inside the module ships with a moved block 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.

WorkspacesOne directory, tfvars per envDirectory per env
Howterraform workspace select prod-var-file=prod.tfvars plus -backend-configcd envs/prod
StateOne backend, one key per workspaceOne key or backend per envOne backend config per env
Code can differ per envOnly through conditionalsOnly through variablesYes, including module versions
Main riskApplying in the wrong workspace; shared credentialsWrong var file with the wrong backendEnvironments slowly diverge
FitsShort-lived copies, per-branch previewsSmall teams, identical environmentsProduction 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.

The default leaves a gap with no server. The second order needs names that can exist twice.
RuleEffectTrap
prevent_destroyAny plan that would destroy the resource failsDeleting the whole block removes the rule with it, and the plan then destroys
create_before_destroyReplacement is created firstFails when a unique name is fixed: both copies need it at once
ignore_changesListed arguments are not corrected after creationignore_changes = all hides real drift
replace_triggered_byReplace this when another resource changesEasy 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.

The plan is made again after merge because main may have moved since the pull request plan.
  • 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.

SymptomCauseFix
"Error acquiring the state lock"Another run is active, or a run was killed before it released the lockConfirm nobody is running, then terraform force-unlock LOCK_ID
Plan wants to change things nobody editedDrift, or a provider that changed a defaultRevert, adopt in code, or ignore_changes for values owned elsewhere
Plan destroys and creates after a refactorRename or index shiftmoved block, for_each
Apply failed halfwayAn API error, a quota, a timeoutFix the cause and apply again: finished resources are already in state. There is no automatic rollback.
"already exists" on createThe resource exists but is not in stateimport it
Large unexpected diff after an upgradeNew provider major version: renamed arguments, changed defaultsSee below
CI fails at init with a checksum errorLock file lacks the CI platformterraform 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.

The same edit, with and without one moved block.
Edit that changes an addressGuard
Renaming a resource or module labelmoved
Moving a resource into or out of a modulemoved
Switching count to for_eachmoved from x[0] to x["key"]
Anything on a database or bucketprevent_destroy, deletion protection on the resource itself, backups

Terraform and its alternatives

Operating

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.

TerraformOpenTofuPulumiCloudFormation
LanguageHCLHCL, same filesPython, Go, TypeScript and othersYAML or JSON
CloudsMany, through providersMany, same provider ecosystemMany, a lot through Terraform providersAWS only
StateYou manage a backend, or use the vendor's serviceSame, plus built-in state encryptionVendor service by default, or your own bucketHeld by AWS, nothing to manage
PreviewplanplanpreviewChange sets
On a failed applyStops, partial result staysSameStops, partial result staysRolls the stack back
LicenceSource available (BSL) since 2023Open source (MPL), a fork under the Linux FoundationOpen source engineProprietary service
Choose whenThe default; the most examples and hiring poolAn open licence matters, or you want its extra featuresInfrastructure needs real loops, types and testsAWS 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 toCommand or block
Set up a fresh checkoutterraform init
Move providers to newer versionsterraform init -upgrade
Format and checkterraform fmt -recursive, terraform validate
See what would changeterraform plan -var-file=prod.tfvars
Apply exactly what was reviewedterraform plan -out=tfplan, then terraform apply tfplan
Read a saved planterraform show tfplan
Look for drift onlyterraform plan -refresh-only
Recreate one resourceterraform apply -replace=ADDR
Work on one resource (emergencies)terraform plan -target=ADDR
List or inspect what is managedterraform state list, terraform state show ADDR
Rename without destroyingmoved { from = ... to = ... }
Adopt an existing resourceimport { to = ... id = "..." }
Forget a resource, keep it runningremoved block or terraform state rm ADDR
Clear a stuck lockterraform force-unlock LOCK_ID
Switch workspaceterraform workspace select NAME
Tear everything downterraform destroy

Interview questions

Operating

QuestionShort 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.