Terraform CLI & IaC State Management Cheat Sheet (2026 Cloud Engineers)
Copy-ready Terraform workflow commands (`init`, `plan`, `apply`), safe state refactoring (`moved`, `import`, `state mv`), workspace separation, and CI drift detection flags.
Exam Code: Terraform · IaC | Track: Cloud & DevOps | Recommended Course: Cloud Infrastructure, Terraform & Kubernetes DevOps Track
Core Terraform Lifecycle, State & Drift Commands
Standard HashiCorp Terraform CLI commands used across AWS, Azure, GCP, and Kubernetes DevOps pipelines.
| Workflow Stage | Terraform CLI Command | Exam / Production Caution |
|---|---|---|
Initialize providers & remote backend | terraform init -upgrade | Run after adding new modules or bumping provider constraints |
Format HCL files recursively | terraform fmt -recursive -check | Enforce CI formatting before PR merge |
Validate HCL syntax without cloud APIs | terraform validate | Fast pre-commit check after variable edits |
Preview execution plan safely to file | terraform plan -out=tfplan | Saves deterministic plan so apply executes exact changes |
Apply saved plan without drift surprises | terraform apply tfplan | Recommended pattern for CI/CD production gates |
Destroy only a targeted resource (careful) | terraform destroy -target=aws_instance.sandbox | Avoid `-target` in daily workflows; reserve for broken resources |
State Inspection, Locking & Zero-Downtime Refactoring
Safely rename resources, import legacy cloud assets, and debug remote state locks.
| Task | Terraform Command | Production Safety Note |
|---|---|---|
List all tracked resources in state | terraform state list | Verify exact module addresses before refactoring |
Rename resource in state without destroying | terraform state mv aws_s3_bucket.old aws_s3_bucket.new | Or use declarative `moved {}` block in HCL (v1.1+) |
Import existing cloud resource into state | terraform import azurerm_resource_group.rg /subscriptions/.../resourceGroups/prod | Or use Terraform 1.5+ declarative `import {}` block |
Detect configuration drift without changes | terraform plan -refresh-only | Reconciles manual portal edits back into state safely |
Switch or isolate env workspaces | terraform workspace select prod || terraform workspace new prod | Isolates state files per environment cleanly |
Frequently Asked Questions
Why is `-replace` preferred over the legacy `terraform taint` command?
Running `terraform apply -replace="resource.name"` previews the exact destroy-and-recreate plan cleanly in a single atomic workflow instead of mutating shared remote state prematurely.