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 StageTerraform CLI CommandExam / Production Caution
Initialize providers & remote backendterraform init -upgradeRun after adding new modules or bumping provider constraints
Format HCL files recursivelyterraform fmt -recursive -checkEnforce CI formatting before PR merge
Validate HCL syntax without cloud APIsterraform validateFast pre-commit check after variable edits
Preview execution plan safely to fileterraform plan -out=tfplanSaves deterministic plan so apply executes exact changes
Apply saved plan without drift surprisesterraform apply tfplanRecommended pattern for CI/CD production gates
Destroy only a targeted resource (careful)terraform destroy -target=aws_instance.sandboxAvoid `-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.

TaskTerraform CommandProduction Safety Note
List all tracked resources in stateterraform state listVerify exact module addresses before refactoring
Rename resource in state without destroyingterraform state mv aws_s3_bucket.old aws_s3_bucket.newOr use declarative `moved {}` block in HCL (v1.1+)
Import existing cloud resource into stateterraform import azurerm_resource_group.rg /subscriptions/.../resourceGroups/prodOr use Terraform 1.5+ declarative `import {}` block
Detect configuration drift without changesterraform plan -refresh-onlyReconciles manual portal edits back into state safely
Switch or isolate env workspacesterraform workspace select prod || terraform workspace new prodIsolates 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.