Terraform Cheats for Debugging
Reading plan output, fixing state, recovering from broken applies. The terraform commands worth memorising.
Reading plans
Reading the plan before apply is the daily discipline. The surprise is always in the diff; saving the plan and applying only the saved file removes the gap between "what I read" and "what runs."
terraform plan -out=plan.tfplan. Saved plan file locks in the exact diff thatapplywill execute. No drift between review and run.terraform show plan.tfplan. Human-readable rendering of the saved plan. Read before apply, every time.- Line-by-line review. Walk every
~,+,-in the diff. Surprise resources usually live in the third screen down. - JSON output for automation.
terraform show -json plan.tfplan | jqfeeds policy checks (OPA, Sentinel) and CI gates.
State surgery
State surgery is the recovery toolkit when reality and state diverge. List, remove, move resources at the state layer without touching the cloud. Always snapshot before cutting.
terraform state list. Tracked-resource inventory for the project. First move when state shape is unclear.terraform state rm. State-only removal. Drops the resource from Terraform's tracking without destroying it in the cloud.terraform state mv. Rename or refactor in place. Moves the resource within state without forcing recreation.- Snapshot before every surgery. Backup the state file before any
rmormv. Catches "I removed the wrong resource" before it lands in the remote backend.
Import
Import recovers from manual changes by pulling existing cloud resources back into Terraform's state. The trick is making the matching config match exactly, then verifying zero drift before the next apply.
terraform import addr id. Pull an existing resource into state by AWS/GCP ID. Required first step before Terraform can manage it.- Recover from click-built resources. Adopt resources someone created in the console during an incident. Cleans up post-incident state drift.
- Matching config required. Import only populates state; the corresponding resource block must already exist in code. Otherwise next plan shows the resource as needing recreation.
- Post-import plan check. Run
terraform planafter every import. Zero drift means the import is clean; non-zero drift means the config and reality disagree.