← All cheatsheets

IaC

Terraform — plan, apply, state, and modules safely

A safe Terraform workflow: init providers, fmt/validate, read the plan diff before you apply, confirm the workspace and backend you are pointed at, and operate state (show/list/mv/rm/import) and modules without surprising production.

Docs-checkedterraformiacstatemodulesplan

Quick reference — reach for these first

initterraform initInstall providers + modules, wire up the backend
planterraform plan -out=PLAN.tfplanPreview add/change/destroy and save the exact plan
applyterraform apply PLAN.tfplanApply the saved plan — no re-diff, no surprises
stateterraform state listList every resource tracked in current state
workspaceterraform workspace showConfirm WHICH workspace before any apply

The plan-before-apply pipeline

Terraform plan-before-apply pipelineinit, fmt and validate, plan, apply, verify, over a locked shared state backend; plan and apply are the critical path.initproviders+backendfmtvalidateapplyverifyplanread +/~/- summarydestroy / state rm = destructivestate backend(locked)readwrite

Text equivalent: A left-to-right pipeline of five stages: init, then fmt plus validate, then plan, then apply, then verify. The plan and apply stages are highlighted as the critical path. A shared state backend cylinder sits below and is read by plan and written by apply, and it is protected by a lock. A note under plan says read the plus, tilde, and minus summary before continuing; a note under apply warns that destroy and state rm are destructive.

Common tasks

Task · Command · Check / confirm

TaskCommandCheck / confirm
Confirm the target context BEFORE touching anythingterraform workspace show && terraform state list | headWorkspace name is the one you intend (e.g. staging, not default/prod)
Init / re-init providers and backendterraform initShows 'Terraform has been successfully initialized!' and locks provider versions in .terraform.lock.hcl
Upgrade provider versions within constraintsterraform init -upgrade.terraform.lock.hcl diff shows only the versions you expect
Canonically format HCLterraform fmt -recursiveLists reformatted files; re-run prints nothing
Validate syntax and referencesterraform validate'Success! The configuration is valid.'
Plan and read the +/-/~ summaryterraform plan -out=PLAN.tfplanFooter 'Plan: A to add, C to change, D to destroy' matches your intent; D is 0 unless you mean it
Apply the SAVED plan (not a fresh diff)terraform apply PLAN.tfplan'Apply complete!' counts equal the saved plan; no new prompt
Scope a plan to one resource while iteratingterraform plan -target=TYPE.NAMEOnly the targeted resource appears; remove -target before the real apply
Pass variables explicitlyterraform plan -var='region=REGION' -var-file=ENV.tfvarsPlan shows the intended values; no 'No value for required variable' errors
Inspect a resource in stateterraform state show TYPE.NAMEAttributes match the live cloud object
Refactor address safely (no destroy/recreate)terraform state mv TYPE.OLD TYPE.NEWFollow-up plan shows 0 to destroy — just the rename
Adopt an existing cloud object into stateterraform import TYPE.NAME CLOUD_IDCAREFUL: next plan shows no destroy and only drift you expect to reconcile
Stop tracking a resource — DESTRUCTIVE to stateterraform state rm TYPE.NAMEDESTRUCTIVE: removes from state (cloud object orphaned); back up state first, confirm address twice
Tear down managed infra — DESTROYS PRODUCTIONterraform plan -destroy -out=DESTROY.tfplanDESTRUCTIVE: review the full destroy list, confirm workspace, then apply the saved destroy plan deliberately

Change one resource safely: fmt → validate → plan → apply → verify

safe-change

1
Confirm you are in the right workspace before anything changes
terraform workspace show
# staging
2
Canonically format the edited config
terraform fmt -recursive
# main.tf
3
Validate references and types
terraform validate
# Success! The configuration is valid.
4
Plan and READ the diff — one in-place change, zero destroys
terraform plan -out=change.tfplan
# ~ aws_instance.web will be updated in-place
#     ~ instance_type = "t3.small" -> "t3.medium"
# Plan: 0 to add, 1 to change, 0 to destroy.
5
Apply the exact saved plan (no re-diff)
terraform apply change.tfplan
# aws_instance.web: Modifying...
# Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
6
Verify state matches intent and re-plan is clean
terraform state show aws_instance.web | grep instance_type && terraform plan
# instance_type = "t3.medium"
# No changes. Your infrastructure matches the configuration.

Troubleshooting — symptom → first check → next check

SymptomFirst checkEstablishesNext check
'Error acquiring the state lock' / LockID shownterraform show lock info; check if a teammate or CI run is mid-applyWhether it is a live operation (wait) or a stale lock from a crashIf truly stale: terraform force-unlock LOCK_ID (confirm the ID matches, never force a live run)
Plan shows changes nobody made in config (drift)terraform plan — read ~ lines; run terraform state show TYPE.NAME vs the consoleSomething changed the resource out-of-band (manual edit, another tool)terraform apply to reconcile to config, OR import/update config to match reality — decide which is source of truth
'No valid credential sources' / 403 from providerConfirm env/profile: echo $AWS_PROFILE; aws sts get-caller-identity (or gcloud/az equivalent)Terraform is authenticating as the wrong (or no) identity/accountExport the correct profile/credentials for the intended account, then re-run plan
'resource already exists' on apply (409/AlreadyExists)terraform state list | grep NAME — is it tracked?The object exists in the cloud but not in stateterraform import TYPE.NAME CLOUD_ID to adopt it, then plan to confirm 0 destroy
'Invalid count argument' / for_each value not known until applyCheck if count/for_each depends on an unknown (computed) attribute of another resourceThe collection keys cannot be resolved at plan timeBase for_each on static/input values (a map/set of strings), or split apply with -target so the dependency exists first
'Backend configuration changed' / 'please run terraform init'Review the backend block diff in git; confirm the backend bucket/key/workspaceBackend or provider requirements changed since last initterraform init (add -reconfigure only if intentionally repointing state; -migrate-state to move existing state)

References

Terraform CLI v1.9+ on macOS/Linux; HCL2 config with a remote backend (S3/GCS/Azure/HCP) that supports state locking.