Written for Terraform 1.6 and later. Newer commands show the version they need, such as (1.14+). Resource addresses such as aws_instance.web, and file, workspace and variable names, are examples, so swap in your own. Most of these also work in OpenTofu if you type tofu in place of terraform; the ones marked Terraform only don't.

Setup and help #

  • Show the Terraform version and provider versionsLinux, macOS, Windows
    terraform version
  • Show the version as JSON for scriptsLinux, macOS, Windows
    terraform version -json
  • List the built-in functions this version has, as JSONLinux, macOS, Windows
    terraform metadata functions -json
  • List every commandLinux, macOS, Windows
    terraform -help
  • Get help for one commandLinux, macOS, Windows
    terraform plan -help
  • Turn on tab completion for commandsLinux, macOS
    terraform -install-autocomplete
  • Run a command against another folderLinux, macOS, Windows
    terraform -chdir=environments/prod plan

Start a project #

  • Set up a folder: download providers and modules, and connect the backendLinux, macOS, Windows
    terraform init
  • Upgrade providers and modules to the newest versions your rules allowLinux, macOS, Windows
    terraform init -upgrade
  • Set up without changing the dependency lock file (fails if it's out of date)Linux, macOS, Windows
    terraform init -lockfile=readonly
  • Set up with backend settings kept in a separate fileLinux, macOS, Windows
    terraform init -backend-config=backend.hcl
  • Move existing state to a new backendLinux, macOS, Windows
    terraform init -migrate-state

    Warning: Copies your state to the new backend. Take a backup with terraform state pull first.

  • Switch backend without moving the stateLinux, macOS, Windows
    terraform init -reconfigure

    Warning: Ignores the state in the old backend. Use -migrate-state if you want to keep it.

  • Set up without a backend, to validate code onlyLinux, macOS, Windows
    terraform init -backend=false
  • Download the modules your code usesLinux, macOS, Windows
    terraform get
  • Update modules to their newest allowed versionsLinux, macOS, Windows
    terraform get -update
  • Show which providers the code needsLinux, macOS, Windows
    terraform providers
  • Record provider checksums for every platform your team usesLinux, macOS, Windows
    terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64
  • Show every provider's schema as JSONLinux, macOS, Windows
    terraform providers schema -json
  • Download the providers into a local folder for offline or air-gapped useLinux, macOS, Windows
    terraform providers mirror ./providers
  • List every module the code declares (1.10+)Linux, macOS, Windows
    terraform modules
  • List every module the code declares as JSON (1.10+)Linux, macOS, Windows
    terraform modules -json

Format and validate #

  • Format the files in this folderLinux, macOS, Windows
    terraform fmt
  • Format files in this folder and every folder below itLinux, macOS, Windows
    terraform fmt -recursive
  • Check formatting without changing files (for CI)Linux, macOS, Windows
    terraform fmt -check -recursive
  • Show what formatting would changeLinux, macOS, Windows
    terraform fmt -diff
  • Check the code is validLinux, macOS, Windows
    terraform validate
  • Get validation results as JSONLinux, macOS, Windows
    terraform validate -json
  • Try out expressions and functions interactivelyLinux, macOS, Windows
    terraform console
  • Work out one expression without opening the consoleLinux, macOS
    echo 'cidrsubnet("10.0.0.0/16", 8, 2)' | terraform console

Plan #

  • Show what would changeLinux, macOS, Windows
    terraform plan
  • Save a plan to a file, to apply exactly that laterLinux, macOS, Windows
    terraform plan -out=tfplan

    Warning: A saved plan can hold secrets in plain text. Don't commit it or leave it lying around.

  • Read a saved planLinux, macOS, Windows
    terraform show tfplan
  • Get a saved plan as JSONLinux, macOS, Windows
    terraform show -json tfplan
  • Set a variable for one runLinux, macOS, Windows
    terraform plan -var="region=eu-west-1"
  • Use a variables fileLinux, macOS, Windows
    terraform plan -var-file=prod.tfvars
  • Plan for one resource onlyLinux, macOS, Windows
    terraform plan -target=aws_instance.web

    Warning: Targeting skips everything else, so the rest of your infrastructure can drift out of step. Use it to recover from problems, not as routine.

  • Show what a destroy would removeLinux, macOS, Windows
    terraform plan -destroy
  • Show how real infrastructure has drifted from the stateLinux, macOS, Windows
    terraform plan -refresh-only
  • Plan faster by skipping the refresh from the providerLinux, macOS, Windows
    terraform plan -refresh=false

    Warning: The plan uses what the state last recorded, so it can miss changes made outside Terraform.

  • Wait for a state lock instead of failing straight awayLinux, macOS, Windows
    terraform plan -lock-timeout=60s
  • Run more operations at once (the default is 10)Linux, macOS, Windows
    terraform plan -parallelism=20
  • Plan without colour codes, for log filesLinux, macOS, Windows
    terraform plan -no-color
  • Show the plan as streaming JSON for tools to readLinux, macOS, Windows
    terraform plan -json
  • Group warnings into a short summaryLinux, macOS, Windows
    terraform plan -compact-warnings
  • Plan without taking a state lockLinux, macOS, Windows
    terraform plan -lock=false

    Warning: Another run could change the state at the same time. Only use this when you're sure nothing else is running.

Apply and destroy #

  • Make the changes, after showing the plan and asking yes or noLinux, macOS, Windows
    terraform apply
  • Apply a saved planLinux, macOS, Windows
    terraform apply tfplan
  • Apply without asking for confirmationLinux, macOS, Windows
    terraform apply -auto-approve

    Warning: Makes the changes without showing you the plan first. Keep it for automation that has already reviewed a plan.

  • Apply with a variables fileLinux, macOS, Windows
    terraform apply -var-file=prod.tfvars
  • Apply one resource onlyLinux, macOS, Windows
    terraform apply -target=aws_instance.web

    Warning: Targeting skips everything else, so the rest of your infrastructure can drift out of step. Use it to recover from problems, not as routine.

  • Destroy one resource and build it againLinux, macOS, Windows
    terraform apply -replace=aws_instance.web

    Warning: Destroys the resource and creates a new one. Anything stored on it is lost and it may come back with a new address.

  • Apply and stream the progress as JSONLinux, macOS, Windows
    terraform apply -json -auto-approve tfplan
  • Run an action defined in the code (1.14+, Terraform only)Linux, macOS, Windows
    terraform apply -invoke=action.aws_lambda_invoke.notify
  • Preview running an action (1.14+, Terraform only)Linux, macOS, Windows
    terraform plan -invoke=action.aws_lambda_invoke.notify
  • Clear the tainted mark so a resource isn't rebuiltLinux, macOS, Windows
    terraform untaint aws_instance.web
  • Update the state to match real infrastructure, changing nothing elseLinux, macOS, Windows
    terraform apply -refresh-only
  • Destroy everything this configuration managesLinux, macOS, Windows
    terraform destroy

    Warning: Deletes real infrastructure and its data. Read the plan it shows before typing yes.

  • Destroy one resourceLinux, macOS, Windows
    terraform destroy -target=aws_instance.web

    Warning: Deletes the real resource, and anything that depends on it.

  • Destroy everything without askingLinux, macOS, Windows
    terraform destroy -auto-approve

    Warning: Deletes real infrastructure and its data with no confirmation.

Outputs and inspection #

  • Show all outputsLinux, macOS, Windows
    terraform output
  • Show one output as plain text, for scriptsLinux, macOS, Windows
    terraform output -raw db_endpoint

    Warning: Prints sensitive outputs in plain text.

  • Show all outputs as JSONLinux, macOS, Windows
    terraform output -json

    Warning: Prints sensitive outputs in plain text.

  • Show everything in the state in readable formLinux, macOS, Windows
    terraform show
  • Show the state as JSONLinux, macOS, Windows
    terraform show -json

    Warning: State can hold passwords and keys in plain text, so treat this output as a secret.

  • Draw the dependency graph as an image (needs Graphviz)Linux, macOS
    terraform graph | dot -Tsvg > graph.svg
  • Draw the graph of a plan instead of the code (needs Graphviz)Linux, macOS, Windows
    terraform graph -type=plan | dot -Tsvg > plan.svg

State #

  • List every resource in the stateLinux, macOS, Windows
    terraform state list
  • List the resources in one moduleLinux, macOS, Windows
    terraform state list module.network
  • Show everything recorded about one resourceLinux, macOS, Windows
    terraform state show aws_instance.web
  • Show a resource made with countLinux, macOS
    terraform state show 'aws_instance.web[0]'
  • Show a resource made with for_each
    Linux, macOS
    terraform state show 'aws_instance.web["blue"]'
    Windows
    terraform state show 'aws_instance.web[\"blue\"]'
  • Find a resource in the state by its provider ID (1.12+)Linux, macOS, Windows
    terraform state list -id=i-0abc123def4567890
  • Show the identity of every resource as JSON (1.12+)Linux, macOS, Windows
    terraform state identities -json
  • Show the identity of one resource as JSON (1.12+)Linux, macOS, Windows
    terraform state identities -json aws_instance.web
  • Rename a resource in the state without rebuilding itLinux, macOS, Windows
    terraform state mv aws_instance.web aws_instance.app

    Warning: Changes the state directly. Rename it in your code as well, or the next plan will want to destroy and recreate it.

  • Preview a state rename without changing anythingLinux, macOS, Windows
    terraform state mv -dry-run aws_instance.web aws_instance.app
  • Stop managing a resource without destroying itLinux, macOS, Windows
    terraform state rm aws_instance.web

    Warning: Terraform forgets the resource, but the real thing keeps running. Remove it from your code too, or the next apply creates a second one.

  • Preview removing a resource from the stateLinux, macOS, Windows
    terraform state rm -dry-run aws_instance.web
  • Download the state to a file as a backupLinux, macOS, Windows
    terraform state pull > backup.tfstate

    Warning: State can hold passwords and keys in plain text, so treat this output as a secret.

  • Upload a state file, replacing the one in the backendLinux, macOS, Windows
    terraform state push backup.tfstate

    Warning: Replaces the state in the backend. Terraform refuses if your file is older than the state already there, unless you add -force. A wrong file here can make it lose track of everything.

  • Point the state at a provider that has movedLinux, macOS, Windows
    terraform state replace-provider hashicorp/aws registry.example.com/acme/aws
  • Remove a lock left behind by a crashed runLinux, macOS, Windows
    terraform force-unlock 6f2c1d0e-1a2b-3c4d-5e6f-7a8b9c0d1e2f

    Warning: Only do this when you're sure nobody else is running Terraform. Unlocking during a real run can corrupt the state.

Import and query #

  • Bring an existing resource under Terraform's managementLinux, macOS, Windows
    terraform import aws_instance.web i-0abc123def4567890
  • Write starter code for resources you're importing with import blocksLinux, macOS, Windows
    terraform plan -generate-config-out=generated.tf
  • Search your cloud account for resources using the list blocks in .tfquery.hcl files (1.14+, Terraform only)Linux, macOS, Windows
    terraform query
  • Search for resources and write import blocks and code for them (1.14+, Terraform only)Linux, macOS, Windows
    terraform query -generate-config-out=generated.tf
  • Get the search results as JSON (1.14+, Terraform only)Linux, macOS, Windows
    terraform query -json
  • Search with a variables file (1.14+, Terraform only)Linux, macOS, Windows
    terraform query -var-file=prod.tfvars

Workspaces #

  • List workspacesLinux, macOS, Windows
    terraform workspace list
  • Show the current workspaceLinux, macOS, Windows
    terraform workspace show
  • Create a workspace and switch to itLinux, macOS, Windows
    terraform workspace new staging
  • Switch workspaceLinux, macOS, Windows
    terraform workspace select staging
  • Switch workspace, creating it if it doesn't existLinux, macOS, Windows
    terraform workspace select -or-create staging
  • Delete a workspaceLinux, macOS, Windows
    terraform workspace delete staging

    Warning: Deletes the workspace's state. Destroy its infrastructure first, or it's left running with nothing managing it.

  • Delete a workspace that still has resources in its stateLinux, macOS, Windows
    terraform workspace delete -force staging

    Warning: The resources keep running but Terraform forgets them. Destroy them first unless you mean to leave them.

Tests #

  • Run the tests in the tests folderLinux, macOS, Windows
    terraform test
  • Run one test fileLinux, macOS, Windows
    terraform test -filter=tests/network.tftest.hcl
  • Show the plan or state for each test as it runsLinux, macOS, Windows
    terraform test -verbose
  • Run the tests with a variables fileLinux, macOS, Windows
    terraform test -var-file=prod.tfvars
  • Run the tests in a different folderLinux, macOS, Windows
    terraform test -test-directory=tests

HCP Terraform #

  • Log in to HCP Terraform and save a tokenLinux, macOS, Windows
    terraform login
  • Remove the saved tokenLinux, macOS, Windows
    terraform logout
  • Log in to Terraform Enterprise or another hostLinux, macOS, Windows
    terraform login app.terraform.io
  • Log out of another hostLinux, macOS, Windows
    terraform logout app.terraform.io

Automation and CI #

  • Set up without stopping to ask questionsLinux, macOS, Windows
    terraform init -input=false
  • Plan in a pipeline and save the resultLinux, macOS, Windows
    terraform plan -input=false -out=tfplan
  • Apply the saved plan in a pipelineLinux, macOS, Windows
    terraform apply -input=false tfplan
  • Make the exit code say whether anything would change (0 no, 1 error, 2 yes)Linux, macOS, Windows
    terraform plan -detailed-exitcode
  • Tell Terraform it's running in automation, for quieter output
    Linux, macOS
    export TF_IN_AUTOMATION=1
    Windows
    $env:TF_IN_AUTOMATION = "1"
  • Set a variable from the environment
    Linux, macOS
    export TF_VAR_region=eu-west-1
    Windows
    $env:TF_VAR_region = "eu-west-1"
  • Add the same options to every planLinux, macOS
    export TF_CLI_ARGS_plan="-parallelism=20"
  • Choose the workspace from the environmentLinux, macOS
    export TF_WORKSPACE=staging
  • Never ask for input in this shell
    Linux, macOS
    export TF_INPUT=0
    Windows
    $env:TF_INPUT = "0"
  • Keep the .terraform working data in another folderLinux, macOS
    export TF_DATA_DIR=.terraform-prod
  • Share downloaded providers between projectsLinux, macOS
    export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Debugging #

  • Turn on debug logging
    Linux, macOS
    export TF_LOG=DEBUG
    Windows
    $env:TF_LOG = "DEBUG"
  • Turn on debug logging for one command onlyLinux, macOS
    TF_LOG=DEBUG terraform plan
  • Log Terraform itself without the provider noiseLinux, macOS
    export TF_LOG_CORE=DEBUG
  • Log only the providersLinux, macOS
    export TF_LOG_PROVIDER=DEBUG
  • Send the most detailed logs to a file
    Linux, macOS
    export TF_LOG=TRACE export TF_LOG_PATH=terraform.log
    Windows
    $env:TF_LOG = "TRACE" $env:TF_LOG_PATH = "terraform.log"
  • Turn logging off again
    Linux, macOS
    unset TF_LOG TF_LOG_PATH
    Windows
    Remove-Item Env:TF_LOG, Env:TF_LOG_PATH