Terraform · Cheat sheet
Terraform cheat sheet
Terraform cheat sheet: init/plan/apply, state, workspaces, variables, modules, import, and debugging with examples.
Rows marked Destructive State operation Caution Exposes secrets can remove data, change authoritative state, affect a running system, or print secrets. Read the note before running them against anything that matters.
Setup & init
Beginnerterraform version- CLI and provider versions.Example output
Terraform v1.16.4 on linux_amd64 + provider registry.terraform.io/hashicorp/aws v6.66.0
terraform init- Download providers/modules and configure the backend.Example output
Initializing the backend... Initializing provider plugins... - Installing hashicorp/aws v6.66.0... Terraform has been successfully initialized!
terraform init -upgrade- Re-fetch providers to the newest allowed versions.
terraform init -reconfigure- Reconfigure the backend, ignoring saved settings.
terraform init -backend-config=prod.hcl- Load backend settings from a partial-config file.
backend "s3" { use_lockfile = true }- S3-native state locking (dynamodb_table locking is deprecated).
terraform get -update- Download/update modules only (no provider work).
terraform login- Obtain and store an HCP Terraform / Cloud token.
terraform -chdir=envs/prod plan- Run in another directory (global flag, before the subcommand).
Core workflow
Beginnerterraform plan- Preview the changes needed to reach desired state.Example output
Plan: 3 to add, 1 to change, 0 to destroy.
terraform plan -out=tfplan- Preview and save the exact plan to a file.
terraform apply- Show a plan, then apply after you type yes.
terraform apply tfplan- Apply a saved plan with no prompt and no surprises.
terraform apply -auto-approveCaution- Skip the confirmation prompt (CI).Caution: Applies the plan, including any destroys, with no review prompt.
terraform destroyDestructive- Tear down everything this config manages.Destructive: Destroys every resource tracked in the current workspace state.
terraform destroy -target=<addr>Destructive- Destroy a single resource.Destructive: Destroys the targeted resource and anything that depends on it.
terraform apply -replace=<addr>Destructive- Force-recreate one resource (replaces old taint).Destructive: Destroys and recreates the resource; data held on it is lost.
Format & validate
Beginnerterraform fmt- Rewrite files to canonical style.
terraform fmt -recursive -check- Fail (exit 3) if any file is unformatted — for CI.
terraform validate- Check syntax and internal consistency (no cloud calls).Example output
Success! The configuration is valid.
terraform plan -detailed-exitcode- 0 = no changes, 1 = error, 2 = changes present. CI gate.
terraform console- Interactive REPL to test expressions against state.Example output
> upper("prod") "PROD" > length(var.subnets) 3
Variables & outputs
Intermediateterraform apply -var="region=us-east-1"- Set one variable on the command line.
terraform apply -var-file=prod.tfvars- Feed a whole environment’s variables.
export TF_VAR_region=us-east-1- Set a variable via the environment.
terraform output- Print all root output values.
terraform output -raw db_endpointExposes secrets- Print one output unquoted (for scripts).Exposes secrets: -raw prints sensitive outputs in plain text.Example output
db.prod.internal:5432
terraform output -jsonExposes secrets- Machine-readable outputs for pipelines.Exposes secrets: Prints sensitive outputs in plain text, e.g. into CI logs.
Inspect state
Intermediateterraform state list- List every resource address in state.Example output
aws_instance.web aws_security_group.web module.vpc.aws_vpc.this
terraform state show <addr>- Show one resource’s recorded attributes.
terraform show- Human-readable dump of current state or a plan.
terraform show -json tfplanExposes secrets- JSON of a saved plan (feed to OPA/Conftest).Exposes secrets: JSON output includes sensitive values in plain text.
terraform graph | dot -Tsvg > g.svg- Render the dependency graph.
terraform plan -refresh-only- Show drift between state and real infra (read-only).
terraform apply -refresh-onlyState operation- Write reviewed drift into state (replaces deprecated refresh).State operation: Writes detected drift into state once you confirm.
State surgery
Advancedterraform state mv <a> <b>State operation- Rename/move a resource without recreating it.State operation: Rewrites state addresses directly; prefer a moved block for review.
terraform state mv <a> module.m.<a>State operation- Move a resource into a module.State operation: Rewrites state addresses directly; prefer a moved block for review.
terraform state rm <addr>State operation- Forget a resource (leaves the real thing alone).State operation: Terraform stops tracking the object; prefer a removed block.
terraform state pull > state.jsonExposes secrets- Download remote state to a local file.Exposes secrets: State holds secrets in plain text; so does the local copy.
terraform state push state.jsonState operation- Overwrite remote state (dangerous — back up first).State operation: Overwrites remote state; a wrong file orphans or duplicates resources.
terraform force-unlock <LOCK_ID>State operation- Release a stuck state lock.State operation: Clearing a live lock lets two runs write state at the same time.
Import & moved
Advancedterraform import <addr> <cloud-id>State operation- Bring an existing resource under management.State operation: Writes to state immediately, with no plan review.Example output
terraform import aws_instance.web i-0abcd1234 Import successful!
import { to = aws_s3_bucket.b id = "my-bucket" }- Declarative import: reviewed in plan, done on apply.
terraform plan -generate-config-out=gen.tf- Generate resource HCL for import blocks (experimental).
moved { from = aws_instance.a to = aws_instance.b }- Refactor addresses with no state mv command.
removed { from = aws_instance.a lifecycle { destroy = false } }- Drop from state, keep the real object (reviewable state rm).
Workspaces
Intermediateterraform workspace list- List workspaces (* marks the active one).Example output
default * staging prod
terraform workspace new prod- Create and switch to an isolated state workspace.
terraform workspace select prod- Switch the active workspace.
terraform.workspace- Interpolation for the current workspace name in HCL.
Debug & maintenance
AdvancedTF_LOG=DEBUG terraform apply- Verbose logs (TRACE/DEBUG/INFO/WARN/ERROR).
TF_LOG_PATH=tf.log TF_LOG=TRACE terraform plan- Send trace logs to a file.
terraform providers- Tree of provider requirements across modules.
terraform providers lock -platform=linux_amd64- Add checksums for another OS to the lock file.
terraform taint <addr>State operation- Deprecated: use apply -replace. Marks it for recreation in state.State operation: Marks the resource in state; the next apply destroys and recreates it.
terraform testCaution- Run .tftest.hcl assertions (native testing, 1.6+).Caution: Creates real infrastructure (and cost), then tries to destroy it.
Related
- ComparisonTerraform vs OpenTofu
- Interview guideTerraform interview questions
- CourseTerraform
- CourseTerraform security and compliance
- CourseOpenTofu
- Field noteTerraform remote state: S3 native locking, migration, and recovery
- Field noteImporting existing infrastructure into Terraform state
- Field noteWriting reusable Terraform modules that don't fight you
Primary references
Found a technical issue on this page? Report it with the tool version you used and the behavior you saw. How resources are maintained.
Go deeper
Hands-on courses for Terraform