Core Workflow
Write → Plan → Apply (→ Destroy)
- init download providers/modules, config backend (-upgrade, -reconfigure, -migrate-state).
- plan dry run; -out=file; -refresh-only (drift).
- apply file = no prompt; -auto-approve; -replace=ADDR.
- destroy = apply -destroy.
- fmt reformat only; validate syntax only, no creds/API.
- console REPL for expressions.
State Commands ★
| Cmd | Effect |
| state list/show | view state |
| state mv | refactor, NO destroy/recreate |
| state rm | forget; does NOT destroy |
| import ADDR ID | add to state; does NOT write config |
Memorize these 3 — the #1 exam trap.
Config-driven: import { to=…, id=… } block + plan -generate-config-out=f.tf scaffolds config.
State Concepts
- Default = local tfstate. Remote: s3, azurerm, gcs, consul, pg, k8s, HCP (cloud block).
- Locking prevents concurrent corruption (S3+DynamoDB; HCP auto). force-unlock, -lock=false.
- State = plaintext incl secrets → never commit; encrypt remote. sensitive=true only hides CLI output.
- terraform_remote_state reads another config's outputs.
- Drift → plan / apply -refresh-only.
Providers
- Plugin architecture; from public Registry; init downloads to .terraform/.
- required_providers { aws = { source="hashicorp/aws", version="~> 5.0" } }
- Constraints: = != >= <= ~>. ~> 5.1=5.x≥5.1 (not 6.0); ~> 5.1.2=5.1.x only.
- .terraform.lock.hcl pins exact versions — commit it. required_version pins CLI.
Modules
- root module calls child modules; vars scoped (no globals).
- Sources: local ./x, Registry ns/name/provider, Git git::…?ref=v1.2.0, S3/GCS/HTTP.
- version only for Registry; Git uses ?ref=; local = no version.
- Inputs = variable blocks; outputs expose to parent.
Variable Precedence
low → high:
- env TF_VAR_*
- terraform.tfvars
- terraform.tfvars.json
- *.auto.tfvars (alpha)
- -var / -var-file (last wins)
Types: string/number/bool · collection list/set/map · structural object/tuple. validation, sensitive, nullable.
count vs for_each
| count | for_each |
| index [0] | key ["k"] |
| N identical | distinguishable items |
| middle remove = reindex churn | stable keys (each.key/value) |
lifecycle
- create_before_destroy build new before kill old.
- prevent_destroy block deletion (plan errors).
- ignore_changes=[attr] ignore drift.
- meta: depends_on, count, for_each, provider.
Resources / Deps
- resource manages; data read-only lookup (refreshed on plan).
- Implicit dep = reference aws_x.id; explicit = depends_on. DAG parallelizes independents.
- Provisioners (local-exec/remote-exec/file) = last resort; prefer native resources. on_failure=continue|fail.
Expressions & Conditions
- Types: primitives + complex (list/set/map, object/tuple).
- Functions (join/split/lookup/merge/length…); test in console.
- Conditional c ? a : b; for expr; dynamic blocks; splat [*].
- validation block on variable; precondition/postcondition in lifecycle; check blocks (warn, non-blocking).
Secrets
- sensitive=true hides CLI output only — still in state.
- Never hard-code secrets / commit secret .tfvars. Inject via TF_VAR_* or a secrets store.
- Pull from Vault provider; ephemeral values don't persist to state.
HCP Terraform
- Remote runs + remote state (auto lock/encrypt).
- VCS integration → PR speculative plans, run triggers.
- Private module/provider registry; org workspaces + projects.
- Sentinel/OPA policy, cost estimation, SSO/RBAC, variable sets.
- Editions Free/Standard/Plus — know Cloud/Ent-only: Sentinel, cost est, run triggers, SSO, state sharing.
CLI workspace (multi state per config, terraform.workspace) ≠ HCP workspace.
IaC / Why Terraform
- IaC = declarative, versioned, repeatable infra → consistency, less human error.
- Terraform: cloud-agnostic, huge provider ecosystem, state for precise planning.
- Declarative (desired state) vs imperative (steps).
Top Traps
state rm≠destroy · import≠config · state mv=refactor · count reindex vs for_each keys · ~> constraint · Cloud-only(Sentinel/cost/run triggers/SSO) · provisioners last resort · validate no creds · apply savedplan no prompt · TF_LOG=TRACE debug
57 Q/60 min ≈ 63s. Fill-in-the-blank → know exact command spelling. Flag & return. Avoid dumps.