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.
Quick reference — reach for these first
terraform initInstall providers + modules, wire up the backendterraform plan -out=PLAN.tfplanPreview add/change/destroy and save the exact planterraform apply PLAN.tfplanApply the saved plan — no re-diff, no surprisesterraform state listList every resource tracked in current stateterraform workspace showConfirm WHICH workspace before any applyThe plan-before-apply pipeline
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
| Task | Command | Check / confirm |
|---|---|---|
| Confirm the target context BEFORE touching anything | terraform workspace show && terraform state list | head | Workspace name is the one you intend (e.g. staging, not default/prod) |
| Init / re-init providers and backend | terraform init | Shows 'Terraform has been successfully initialized!' and locks provider versions in .terraform.lock.hcl |
| Upgrade provider versions within constraints | terraform init -upgrade | .terraform.lock.hcl diff shows only the versions you expect |
| Canonically format HCL | terraform fmt -recursive | Lists reformatted files; re-run prints nothing |
| Validate syntax and references | terraform validate | 'Success! The configuration is valid.' |
| Plan and read the +/-/~ summary | terraform plan -out=PLAN.tfplan | Footer '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 iterating | terraform plan -target=TYPE.NAME | Only the targeted resource appears; remove -target before the real apply |
| Pass variables explicitly | terraform plan -var='region=REGION' -var-file=ENV.tfvars | Plan shows the intended values; no 'No value for required variable' errors |
| Inspect a resource in state | terraform state show TYPE.NAME | Attributes match the live cloud object |
| Refactor address safely (no destroy/recreate) | terraform state mv TYPE.OLD TYPE.NEW | Follow-up plan shows 0 to destroy — just the rename |
| Adopt an existing cloud object into state | terraform import TYPE.NAME CLOUD_ID | CAREFUL: next plan shows no destroy and only drift you expect to reconcile |
| Stop tracking a resource — DESTRUCTIVE to state | terraform state rm TYPE.NAME | DESTRUCTIVE: removes from state (cloud object orphaned); back up state first, confirm address twice |
| Tear down managed infra — DESTROYS PRODUCTION | terraform plan -destroy -out=DESTROY.tfplan | DESTRUCTIVE: 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
terraform workspace show
# stagingterraform fmt -recursive
# main.tfterraform validate
# Success! The configuration is valid.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.terraform apply change.tfplan
# aws_instance.web: Modifying...
# Apply complete! Resources: 0 added, 1 changed, 0 destroyed.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
| Symptom | First check | Establishes | Next check |
|---|---|---|---|
| 'Error acquiring the state lock' / LockID shown | terraform show lock info; check if a teammate or CI run is mid-apply | Whether it is a live operation (wait) or a stale lock from a crash | If 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 console | Something 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 provider | Confirm env/profile: echo $AWS_PROFILE; aws sts get-caller-identity (or gcloud/az equivalent) | Terraform is authenticating as the wrong (or no) identity/account | Export 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 state | terraform import TYPE.NAME CLOUD_ID to adopt it, then plan to confirm 0 destroy |
| 'Invalid count argument' / for_each value not known until apply | Check if count/for_each depends on an unknown (computed) attribute of another resource | The collection keys cannot be resolved at plan time | Base 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/workspace | Backend or provider requirements changed since last init | terraform init (add -reconfigure only if intentionally repointing state; -migrate-state to move existing state) |
References
- Terraform CLI — command referencedeveloper.hashicorp.com
- terraform plandeveloper.hashicorp.com
- Manage state (state subcommands)developer.hashicorp.com
- Import existing resourcesdeveloper.hashicorp.com
- State locking & backendsdeveloper.hashicorp.com
Terraform CLI v1.9+ on macOS/Linux; HCL2 config with a remote backend (S3/GCS/Azure/HCP) that supports state locking.