man terraform

TF Cheatsheet

The Terraform CLI on one page: the daily init, plan and apply loop, variables and outputs, state surgery, imports and refactoring blocks, workspaces, providers, targeting, testing and debugging, and HCP Terraform. Every command comes with a real example, and the notes call out what changed up to Terraform 1.17.

Showing 64 of 64 commands

Everyday workflow

12 commands

The init, fmt, validate, plan and apply loop you run dozens of times a day.

terraform init beginner Prepare a working directory: download providers and modules and connect the state backend.

Example

bash
terraform init
# Quieter output in CI
terraform init -input=false -no-color
Initializing the backend...
Initializing provider plugins...
- Installing hashicorp/aws v6.18.0...

Terraform has been successfully initialized!

Tip: Run it after cloning a repo and whenever you change providers, modules or the backend block.

terraform init -upgrade intermediate Re-run init and pick the newest provider and module versions your constraints allow.

Example

bash
terraform init -upgrade
git diff .terraform.lock.hcl
- Installing hashicorp/aws v6.19.0...

Terraform has been successfully initialized!

Tip: Review the lock file diff in a pull request: it is the record of exactly which provider builds you run.

terraform init -backend-config=<file> intermediate Fill in backend settings from a file or key=value pairs, so one configuration can point at several state locations.

Example

bash
terraform init -backend-config=backends/prod.s3.tfbackend
terraform init -backend-config="key=orbit/staging.tfstate"

Tip: Keep bucket names and keys out of the code and choose them per environment at init time.

terraform init -migrate-state advanced Copy existing state to a new backend after you change the backend block.

Example

bash
terraform init -migrate-state
Do you want to copy existing state to the new backend?
  Enter a value: yes

Successfully configured the backend "s3"!

Tip: Use -reconfigure instead when you want to point at the new backend without copying anything.

terraform fmt beginner Rewrite .tf files in the canonical style; prints the files it changed.

Example

bash
terraform fmt -recursive
# Fail in CI when something is not formatted
terraform fmt -check -diff -recursive
main.tf
modules/network/variables.tf

Tip: Add fmt -check to the pipeline and to a pre-commit hook so style never shows up in reviews.

terraform validate beginner Check syntax, types and references without touching any API.

Example

bash
terraform validate
# Machine-readable result for CI
terraform validate -json
Success! The configuration is valid.

Tip: Needs an initialized directory; in CI run terraform init -backend=false first so no state access is required.

terraform plan beginner Compare code, state and real infrastructure and print what apply would create, change or destroy.

Example

bash
terraform plan
# Only the summary line counts
terraform plan -compact-warnings | tail -n 1
  # aws_s3_bucket.notes will be created
  + resource "aws_s3_bucket" "notes" {
      + bucket = "orbit-notes-staging"
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Tip: Read every plan before applying and search it for "destroy" and "must be replaced".

terraform plan -out=<file> intermediate Save the plan to a file so apply later does exactly what was reviewed.

Example

bash
terraform plan -out=orbit.tfplan
terraform apply orbit.tfplan
Saved the plan to: orbit.tfplan

To perform exactly these actions, run the following command to apply:
    terraform apply "orbit.tfplan"

Tip: Plan files can contain sensitive values; treat them like secrets and never commit them.

terraform plan -minimal-refresh advanced Only refresh resources that have proposed changes, which speeds up plans on very large states (Terraform 1.17+).

Example

bash
terraform plan -minimal-refresh

Tip: Faster, but drift on untouched resources is not detected; keep a scheduled full plan for drift checks.

terraform apply beginner Make the changes: Terraform plans again, shows the plan and waits for you to type yes.

Example

bash
terraform apply
# Apply a saved, already reviewed plan (no prompt)
terraform apply orbit.tfplan
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
terraform apply -auto-approve intermediate Apply without the confirmation prompt.

Example

bash
terraform apply -auto-approve -input=false

Tip: Fine for throwaway sandboxes; in pipelines prefer applying a saved plan that a person approved.

terraform destroy intermediate Delete everything this configuration manages in the current workspace, after a confirmation.

Example

bash
terraform workspace show
terraform destroy
# Preview the destruction first
terraform plan -destroy
Plan: 0 to add, 0 to change, 4 to destroy.
...
Destroy complete! Resources: 4 destroyed.

Tip: Check the workspace and backend before typing yes; protect critical resources with lifecycle { prevent_destroy = true }.

Variables and outputs

7 commands

Feed values into a configuration and read the results back out.

terraform plan -var="<name>=<value>" beginner Set one input variable on the command line.

Example

bash
terraform plan -var="environment=staging" -var="instance_count=2"

Tip: Quote the whole flag so your shell does not split values with spaces or special characters.

terraform plan -var-file=<file> beginner Load many variables from a .tfvars or .tfvars.json file.

Example

bash
terraform plan -var-file=env/production.tfvars
terraform apply -var-file=env/production.tfvars

Tip: terraform.tfvars and *.auto.tfvars load automatically; any other file needs -var-file.

TF_VAR_<name>=<value> terraform plan intermediate Pass a variable through the environment, handy for secrets in CI.

Example

bash
export TF_VAR_db_password="$DB_PASSWORD"
terraform plan

Tip: Mark such variables sensitive = true, or ephemeral = true (1.10+) so they never land in state or plan files.

terraform output beginner Print every root module output from the current state.

Example

bash
terraform output
bucket_name = "orbit-notes-prod"
web_url     = "https://orbit.example.com"
db_password = <sensitive>

Tip: Sensitive outputs are hidden here; ask for one by name to see it.

terraform output <name> beginner Print a single output.

Example

bash
terraform output web_url
"https://orbit.example.com"
terraform output -raw <name> intermediate Print a string output without quotes, ready to pipe into other commands.

Example

bash
curl -fsS "$(terraform output -raw web_url)/health"
ok

Tip: -raw only works for strings, numbers and booleans; use -json for lists and maps.

terraform output -json intermediate Print outputs as JSON for scripts and other tools.

Example

bash
terraform output -json | jq -r '.bucket_name.value'
orbit-notes-prod

Tip: JSON output reveals sensitive values; do not print it in shared CI logs.

State

9 commands

Look inside the state file and fix it without touching real infrastructure.

terraform state list beginner List every resource address tracked in state.

Example

bash
terraform state list
# Narrow down a large state
terraform state list module.network
aws_s3_bucket.notes
module.network.aws_subnet.private[0]
module.network.aws_subnet.private[1]
module.network.aws_vpc.main
terraform state show <address> intermediate Show all stored attributes of one resource.

Example

bash
terraform state show aws_s3_bucket.notes
# Quote addresses with brackets
terraform state show 'module.network.aws_subnet.private[0]'
# aws_s3_bucket.notes:
resource "aws_s3_bucket" "notes" {
    arn    = "arn:aws:s3:::orbit-notes-prod"
    bucket = "orbit-notes-prod"
    region = "eu-west-1"
}

Tip: Terraform 1.16+ also accepts -json here for scripting.

terraform state mv <from> <to> advanced Rename an address in state so Terraform does not destroy and recreate the object.

Example

bash
terraform state mv aws_instance.api module.compute.aws_instance.api
Move "aws_instance.api" to "module.compute.aws_instance.api"
Successfully moved 1 object(s).

Tip: Prefer a moved block in code: it is reviewed in the pull request and works for everyone who applies.

terraform state rm <address> advanced Stop managing an object: it leaves state but keeps running in the cloud.

Example

bash
terraform state rm aws_security_group.legacy
Removed aws_security_group.legacy
Successfully removed 1 resource instance(s).

Tip: Since 1.7 a removed block with lifecycle { destroy = false } does the same thing through a reviewed change.

terraform state pull intermediate Download the current state as JSON to stdout.

Example

bash
terraform state pull > backup-$(date +%F).tfstate
terraform state pull | jq '.serial'
42

Tip: Take a copy like this before any manual state surgery.

terraform state push <file> advanced Overwrite the remote state with a local file.

Example

bash
terraform state push fixed.tfstate

Tip: Last resort only. Terraform refuses if the serial or lineage looks wrong; -force bypasses that, so back up first.

terraform state replace-provider <old> <new> advanced Point resources in state at a different provider source, for example after moving to a private registry mirror.

Example

bash
terraform state replace-provider hashicorp/aws registry.example.com/platform/aws
Terraform will perform the following actions:
  ~ Updating provider:
    - registry.terraform.io/hashicorp/aws
    + registry.example.com/platform/aws

Successfully replaced provider for 12 resources.
terraform force-unlock <lock-id> advanced Release a state lock left behind by a crashed or cancelled run.

Example

bash
terraform force-unlock 9f1c2e3a-4b5d-6e7f-8a9b-0c1d2e3f4a5b
Terraform state has been successfully unlocked!

Tip: Copy the lock ID from the error message, and make sure nobody, including a CI job, is still running.

terraform apply -refresh-only intermediate Update state to match the real infrastructure without changing any resources.

Example

bash
terraform plan -refresh-only
terraform apply -refresh-only
Note: Objects have changed outside of Terraform
...
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Tip: Replaces the deprecated terraform refresh, and shows you the drift before accepting it.

Import and refactoring

6 commands

Bring existing resources under Terraform and reorganize code without recreating anything.

import { to, id } block intermediate Declare an import in code; the next plan shows it and apply adopts the object (Terraform 1.5+).

Example

bash
cat >> imports.tf <<'EOF'
import {
  to = aws_s3_bucket.logs
  id = "orbit-access-logs"
}
EOF
terraform plan
  # aws_s3_bucket.logs will be imported

Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.

Tip: Import blocks are reviewed like any change and work in CI; delete them after the apply if you like.

terraform plan -generate-config-out=<file> intermediate Write resource blocks for import targets that have no configuration yet.

Example

bash
terraform plan -generate-config-out=generated.tf
Terraform has generated configuration and written it to generated.tf.

Tip: Treat the generated code as a draft: remove computed attributes and replace hard-coded IDs with references.

terraform import <address> <id> advanced Adopt one existing object into state immediately (the older CLI way).

Example

bash
terraform import aws_s3_bucket.logs orbit-access-logs
aws_s3_bucket.logs: Importing from ID "orbit-access-logs"...

Import successful!

Tip: Write the resource block first. Prefer import blocks for anything that should be reviewed.

moved { from, to } block intermediate Record a rename or a move into a module so plan shows a move instead of destroy and create.

Example

bash
cat >> moved.tf <<'EOF'
moved {
  from = aws_instance.api
  to   = module.compute.aws_instance.api
}
EOF
terraform plan
  # aws_instance.api has moved to module.compute.aws_instance.api

Plan: 0 to add, 0 to change, 0 to destroy.

Tip: Keep moved blocks in shared modules for a few releases so every consumer gets the move.

removed { from } block advanced Remove a resource from the configuration and decide whether the real object is destroyed (Terraform 1.7+).

Example

bash
cat >> removed.tf <<'EOF'
removed {
  from = aws_security_group.legacy
  lifecycle {
    destroy = false
  }
}
EOF
terraform plan
  # aws_security_group.legacy will no longer be managed by Terraform, but will not be destroyed

Plan: 0 to add, 0 to change, 0 to destroy.
terraform query advanced Run list blocks from *.tfquery.hcl files to discover existing resources, optionally generating import code (Terraform 1.14+).

Example

bash
terraform query
# Generate import and resource blocks for the results
terraform query -generate-config-out=discovered.tf

Tip: Needs a provider that supports list resources; check the provider docs for which types can be listed.

Workspaces

5 commands

Keep several separate states for the same configuration.

terraform workspace list beginner Show all workspaces; the current one is marked with an asterisk.

Example

bash
terraform workspace list
  default
* staging
  production

Tip: Terraform 1.16+ adds -json for scripts.

terraform workspace show beginner Print the name of the current workspace.

Example

bash
terraform workspace show
staging

Tip: Put it in your shell prompt; applying to the wrong workspace is a classic mistake.

terraform workspace new <name> beginner Create a workspace with its own empty state and switch to it.

Example

bash
terraform workspace new review-142
Created and switched to workspace "review-142"!
terraform workspace select <name> beginner Switch to another workspace.

Example

bash
terraform workspace select production
# Create it if it does not exist yet
terraform workspace select -or-create review-142
Switched to workspace "production".

Tip: In CI set TF_WORKSPACE instead of running select.

terraform workspace delete <name> intermediate Delete a workspace whose state is empty.

Example

bash
terraform workspace select default
terraform workspace delete review-142
Deleted workspace "review-142"!

Tip: Destroy its resources first; -force deletes a non-empty state and leaves the resources orphaned.

Modules and providers

6 commands

Fetch modules, inspect providers and keep their versions pinned.

terraform get beginner Download the modules the configuration calls, without touching providers or the backend.

Example

bash
terraform get
# Refresh modules to the newest allowed versions
terraform get -update
Downloading registry.terraform.io/terraform-aws-modules/vpc/aws 6.5.0 for network...

Tip: terraform init does this too; get is just the faster, narrower option.

terraform modules intermediate List the modules declared in the configuration and their sources (Terraform 1.10+).

Example

bash
terraform modules
terraform modules -json | jq '.modules[].source'
terraform providers intermediate Show which providers each module needs and which are recorded in state.

Example

bash
terraform providers
Providers required by configuration:
.
├── provider[registry.terraform.io/hashicorp/aws] ~> 6.0
└── module.network
    └── provider[registry.terraform.io/hashicorp/aws] >= 5.0

Tip: Use it to find the module that holds back a provider upgrade.

terraform providers lock -platform=<os_arch> advanced Record provider checksums for several platforms in .terraform.lock.hcl.

Example

bash
terraform providers lock \
  -platform=linux_amd64 \
  -platform=linux_arm64 \
  -platform=darwin_arm64 \
  -platform=windows_amd64
Success! Terraform has updated the lock file.

Tip: Do this when the team uses different OSes than CI, then commit the lock file.

terraform providers mirror <dir> advanced Copy the required providers into a local directory for air-gapped or cached installs.

Example

bash
terraform providers mirror -platform=linux_amd64 ./mirror
- Mirroring hashicorp/aws...
  - Selected v6.19.0 to match dependency lock file
  - Downloading package for linux_amd64...

Tip: Point Terraform at the folder with a filesystem_mirror block in the CLI config file.

terraform providers schema -json advanced Dump the full schema of every provider in use, useful for editors and code generators.

Example

bash
terraform providers schema -json | jq '.provider_schemas | keys'
[
  "registry.terraform.io/hashicorp/aws"
]

Targeting and replacement

7 commands

Limit a run to some resources or force one to be rebuilt. For exceptions, not daily use.

terraform plan -target=<address> advanced Plan only the given resource or module and the things it depends on.

Example

bash
terraform plan -target=module.network
terraform plan -target='aws_subnet.private["a"]'
Warning: Resource targeting is in effect
...
Plan: 3 to add, 0 to change, 0 to destroy.

Tip: Targeting hides the rest of the plan; always follow up with a full plan so state and code agree.

terraform apply -target=<address> advanced Apply only part of the configuration.

Example

bash
terraform apply -target=aws_s3_bucket.notes
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Tip: Useful to break a dependency deadlock or recover from an incident, never as a normal workflow.

terraform apply -replace=<address> intermediate Destroy and recreate one resource even though its configuration did not change.

Example

bash
terraform plan -replace=aws_instance.api
terraform apply -replace=aws_instance.api
  # aws_instance.api will be replaced, as requested
-/+ resource "aws_instance" "api" {

Plan: 1 to add, 0 to change, 1 to destroy.

Tip: The modern replacement for terraform taint: you see the effect in the plan before anything happens.

terraform destroy -target=<address> advanced Destroy one resource and whatever depends on it.

Example

bash
terraform destroy -target=aws_instance.debug
Destroy complete! Resources: 1 destroyed.

Tip: If the resource is still in the code, the next plan creates it again; remove it from code instead when you can.

terraform plan -refresh=false intermediate Plan from the stored state without asking APIs for the current situation.

Example

bash
terraform plan -refresh=false

Tip: Much faster on big states, but blind to drift. Good for quick checks of a code change.

terraform apply -parallelism=<n> advanced Change how many resource operations run at the same time (default 10).

Example

bash
terraform apply -parallelism=4

Tip: Lower it when an API rate-limits you; raise it carefully for large independent changes.

terraform taint <address> advanced Deprecated: mark a resource for recreation on the next apply.

Example

bash
terraform taint aws_instance.api
# Undo
terraform untaint aws_instance.api
Resource instance aws_instance.api has been marked as tainted.

Tip: Use apply -replace instead; taint changes state immediately without showing a plan.

Inspect, test and debug

7 commands

See what Terraform knows, try expressions, run tests and turn on logs when things go wrong.

terraform show beginner Print the current state, or a saved plan file, in readable form.

Example

bash
terraform show
terraform show orbit.tfplan
terraform show -json <planfile> advanced Convert a saved plan to JSON for policy checks and pipeline gates.

Example

bash
terraform show -json orbit.tfplan \
  | jq -r '.resource_changes[] | select(.change.actions | index("delete")) | .address'
aws_instance.api

Tip: A small jq like this can fail a pipeline whenever a plan wants to delete something.

terraform console intermediate Open an interactive prompt to evaluate expressions against your variables, locals and state.

Example

bash
terraform console
# One-off evaluation from a script
echo 'cidrsubnet("10.0.0.0/16", 8, 2)' | terraform console
"10.0.2.0/24"

Tip: The quickest way to debug a for expression or a tricky function call.

terraform test intermediate Run the *.tftest.hcl test files of a module (Terraform 1.6+).

Example

bash
terraform test
terraform test -filter=tests/naming.tftest.hcl -verbose
tests/naming.tftest.hcl... in progress
  run "bucket_name_has_env"... pass
  run "rejects_bad_env"... pass
tests/naming.tftest.hcl... pass

Success! 2 passed, 0 failed.

Tip: Use command = plan and mock_provider blocks for fast tests that create nothing.

terraform graph intermediate Print the dependency graph in DOT format.

Example

bash
terraform graph | dot -Tsvg > graph.svg

Tip: Needs Graphviz for dot; most useful on small modules, large graphs get unreadable fast.

terraform version beginner Show the Terraform version, provider versions and whether an update exists.

Example

bash
terraform version
terraform version -json
Terraform v1.17.1
on linux_amd64
+ provider registry.terraform.io/hashicorp/aws v6.19.0

Tip: Pin the CLI version for the team with required_version and a tool like tfenv, mise or asdf.

TF_LOG=<level> terraform <command> intermediate Turn on internal logs: TRACE, DEBUG, INFO, WARN or ERROR.

Example

bash
TF_LOG=DEBUG terraform plan
# Only the provider's logs, written to a file
TF_LOG_PROVIDER=DEBUG TF_LOG_PATH=tf.log terraform apply

Tip: Start with DEBUG; TRACE is very verbose. Logs may contain secrets, so never paste them publicly unredacted.

HCP Terraform and registry

5 commands

Sign in to HCP Terraform or a private registry and work with remote runs.

terraform login beginner Get an API token for HCP Terraform (or another host) and save it in the CLI credentials file.

Example

bash
terraform login
terraform login tfe.example.com
Terraform will request an API token for app.terraform.io using your browser.
...
Retrieved token for user jeferson

Tip: In CI use the TF_TOKEN_app_terraform_io environment variable instead of an interactive login.

terraform logout beginner Remove the saved token for a host.

Example

bash
terraform logout
terraform logout tfe.example.com
Removing the stored credentials for app.terraform.io from the following file:
  /home/jeferson/.terraform.d/credentials.tfrc.json

Success! Terraform has removed the stored API token for app.terraform.io.
terraform init (cloud block) intermediate Connect a configuration to HCP Terraform workspaces through a cloud block, then plan and apply run remotely.

Example

bash
cat > cloud.tf <<'EOF'
terraform {
  cloud {
    organization = "orbit-team"
    workspaces {
      tags = ["orbit"]
    }
  }
}
EOF
terraform init
Initializing HCP Terraform...

HCP Terraform has been successfully initialized!

Tip: With tag-based workspaces, terraform workspace select switches between the matching remote workspaces.

terraform plan (remote run) intermediate Start a speculative plan in HCP Terraform and stream its logs to your terminal.

Example

bash
terraform plan
Running plan in HCP Terraform. Output will stream here. Pressing Ctrl-C
will stop streaming the logs, but will not stop the plan running remotely.

Tip: Variables come from the remote workspace, not from your local tfvars files.

TF_TOKEN_<host>=<token> intermediate Provide a registry or HCP Terraform token through the environment, with dots in the hostname written as underscores.

Example

bash
export TF_TOKEN_app_terraform_io="$HCP_TF_TOKEN"
export TF_TOKEN_registry_example_com="$REGISTRY_TOKEN"
terraform init

Tip: The standard way to authenticate private modules and providers in pipelines.

↑ ↓ navigate Enter open Esc close