Terraform commands

Terraform v1.16 command lines, checked against the HashiCorp command reference and the built-in help of release 1.16.5, grouped by task: init, plan and apply, variables, state, imports, workspaces, providers, tests and environment variables. Words in capitals such as ADDRESS, PATH or NAME stand for your own value; names like aws_instance.example come from the documentation. Options follow the subcommand; global options such as terraform -chdir=DIR SUBCOMMAND go before it. The terraform stacks subcommands and legacy local-backend options are left out.

144 commands in 12 sections. Checked row by row against HashiCorp Developer, Terraform v1.16.x documentation: terraform init command reference on . Edited by Jay.

Initialising a working directory 12

CommandWhat it does
terraform initInitialise the working directoryFirst command to run in a new or cloned configuration; sets up the backend, modules and providers and is safe to repeat.
terraform init -upgradeUpgrade modules and providersInstalls the newest versions the constraints allow, ignoring the selections saved in the dependency lock file.
terraform init -backend-config=PATHPass backend settingsMerges an HCL file or a single key=value pair into the backend block; repeat the option for more values.
terraform init -reconfigureReconfigure the backendDiscards the stored backend settings and does not migrate existing state.
terraform init -migrate-stateMigrate state to a new backendSwitches to the changed backend settings and tries to copy the current state across, asking for confirmation where needed.
terraform init -force-copySkip state copy promptsAnswers yes to every question about copying state when a new backend is initialised.
terraform init -backend=falseSkip backend initialisationPrepares a directory for validate without contacting a remote backend; anything initialised earlier stays in use.
terraform init -input=falseDisable init promptsA step that needs an answer then fails with an error instead of waiting.
terraform init -get=falseSkip module downloadLeaves child modules alone; meant for directories whose module tree is already installed.
terraform init -from-module=SOURCECopy a module before initCopies the named module into an empty target directory, then initialises it.
terraform init -lockfile=MODESet the lock file modeThe only mode is readonly, which verifies checksums against the lock file without changing it.
terraform init -jsonPrint init progress as JSONReplaces the human-readable log with JSON messages for other programs to read.

Planning and applying 16

When no saved plan file is passed, apply accepts every planning mode and planning option of plan, including -destroy, -refresh-only, -replace, -var and -var-file.

CommandWhat it does
terraform planPreview the changesCompares the configuration with real infrastructure and prints the proposed actions without carrying any of them out.
terraform plan -out=PATHSave the plan to a fileThe saved file can be handed to apply later, so exactly the reviewed actions are carried out.
terraform applyApply the changesCreates a new plan, shows it and waits for approval before creating, updating or deleting anything.
terraform apply PLANApply a saved planCarries out the actions stored in a file written by plan -out, without asking for confirmation.
terraform apply -auto-approveApply without the approval promptCovers destructive changes too; the flag is ignored when a saved plan file is passed.
terraform destroyDestroy all managed objectsA convenience alias for apply -destroy that removes everything the configuration manages.
terraform apply -destroyApply in destroy modeThe full form that terraform destroy stands for; it takes the same options as apply.
terraform plan -destroyPreview a destroyShows what a destroy would remove, without executing it.
terraform plan -refresh-onlyCheck for drift onlyReports where remote objects differ from the last apply, without proposing actions to undo that drift.
terraform apply -refresh-onlySync state with real objectsShows the differences found outside Terraform and asks before writing them to the state.
terraform refreshRefresh state (deprecated)Deprecated alias for apply -refresh-only -auto-approve, which rewrites the state with no chance to review.
terraform plan -refresh=falseSkip the refresh stepPlans faster by not checking remote objects, at the risk of working from a stale state.
terraform plan -lock=falsePlan without a state lockDangerous if another person or pipeline works on that workspace at the same moment.
terraform apply -lock-timeout=0sSet the lock wait timeKeeps retrying for the state lock for the given duration; 0s, the default, fails at once.
terraform plan -parallelism=NLimit concurrent operationsCaps how many operations run at once; the default is 10.
terraform plan -compact-warningsShorten warning outputPrints only the summary line of each warning, as long as no errors accompany them.

Variables and targeting 7

Terraform reports an error when a -var value has a space before or after its equals sign.

CommandWhat it does
terraform plan -var 'NAME=VALUE'Set one input variableSingle quotes keep a Unix shell from altering the value; repeat the option for each further variable.
terraform plan -var-file=FILENAMELoad variables from a fileReads a variables file on top of terraform.tfvars and *.auto.tfvars, which load automatically.
export TF_VAR_region=us-west-1Set a variable from the environmentAny TF_VAR_ prefix followed by a variable name works; Terraform checks this source last.
terraform plan -target=ADDRESSPlan only one resourceRestricts the plan to the matching resource instances and what they depend on; meant for exceptional situations.
terraform plan -replace=ADDRESSForce replacement of an instancePlans a replace action for that instance where an update or no change would otherwise be planned.
terraform apply -replace="aws_instance.example[0]"Replace one instance on applyThe recommended successor to taint: the replacement appears in the plan before anything is changed.
terraform destroy -target aws_instance.exampleDestroy a single resourceDestroys just the aws_instance labelled example and its dependencies instead of the whole configuration.

Formatting and validating 11

CommandWhat it does
terraform fmtFormat configuration filesRewrites the files in the current directory to the canonical style and lists the ones it changed.
terraform fmt -checkCheck formatting onlyWrites nothing and exits non-zero when any file needs formatting, naming those files.
terraform fmt -diffShow formatting diffsPrints each pending change as a diff, which helps when reviewing what fmt would alter.
terraform fmt -recursiveFormat subdirectories tooWithout it only the given directory, or the current one, is handled.
terraform fmt -write=falseLeave source files untouchedReports formatting problems without rewriting anything; -check and standard input imply it.
terraform fmt -list=falseHide the changed-file listStops fmt from printing the names of files that are not in the standard style.
terraform fmt -Format standard inputA single dash as the target makes fmt read the configuration from stdin instead of scanning a directory.
terraform validateValidate the configurationChecks syntax and internal consistency in an initialised directory; remote state and provider APIs are not contacted.
terraform validate -jsonValidation result as JSONMeant for editor integrations and other tools; colour is always switched off.
terraform validate -no-testsSkip test filesChecks the configuration only and leaves the test files of the module unvalidated.
terraform validate -queryAlso validate query filesExtends the check to .tfquery.hcl files as well.

Inspecting state and outputs 17

CommandWhat it does
terraform showShow the current statePrints the latest state snapshot in readable form when no file path is given.
terraform show FILEInspect a saved plan fileTakes the path of a plan or state file, so a saved plan can be read before it is applied.
terraform show -jsonState or plan as JSONSensitive values held in the state are printed in plain text in this format.
terraform outputList root module outputsReads the values from the state file; outputs of child modules are not shown.
terraform output NAMEPrint one output valueAn output requested by name is printed unredacted even when it is marked sensitive.
terraform output -jsonOutputs as JSONThe stable format for scripts; a parser such as jq can pick values out of it.
terraform output -raw NAMEPrint an output as raw textWorks for string, number and boolean values only and adds no formatting, which suits shell scripts.
terraform state listList resources in stateLists every tracked resource address, root module first and deeper modules last.
terraform state list ADDRESSFilter the resource listShows only resources that match the given resource or module addresses.
terraform state list -id=IDFind a resource by IDKeeps only the instances whose id attribute equals the value given.
terraform state show ADDRESSShow one resource's attributesThe address has to point at a single resource in the state.
terraform state show -json ADDRESSResource attributes as JSON
terraform state identities -jsonList resource identitiesPrints the identity of each resource instance as JSON; add addresses to filter by resource or module.
terraform state pullPrint the raw stateFetches the state from wherever it is stored, upgrades it to the current file version and writes it to stdout.
terraform graphPrint the dependency graphOutputs a simplified graph of the ordering between resources, written in the DOT language.
terraform graph -type=plan | dot -Tpng >graph.pngRender the plan graph as PNGPipes the detailed plan graph into the Graphviz dot command, which must be installed.
terraform graph -format=FORMATChoose the graph formatAccepts dot, which is the default, or mermaid.

State surgery 12

Quotes inside a resource address, as in aws_instance.baz["key"], must be escaped on the command line so that the shell does not interpret them.

CommandWhat it does
terraform stateState subcommand groupParent of list, show, mv, rm, pull, push and replace-provider; subcommands that modify state write a backup file first.
terraform state mv SOURCE DESTINATIONRename or move a resourceTracks an existing object under a new address, for example after renaming a resource block or moving it into a module.
terraform state mv -dry-run SOURCE DESTINATIONPreview a state moveReports the planned move and leaves the state as it is.
terraform state rm ADDRESSStop managing a resourceDeletes the record from state while the remote object keeps existing; the next plan proposes creating it again.
terraform state rm -dry-run ADDRESSPreview a state removalNames the instances that match the address without forgetting any of them.
terraform state push PATHUpload a local state fileWrites the file to the configured backend once lineage and serial checks pass; a path of - reads from stdin.
terraform state push -force PATHPush state past safety checksOverrides the lineage and serial-number checks, so the destination state is overwritten; not recommended.
terraform state replace-provider FROM_PROVIDER_FQN TO_PROVIDER_FQNChange a provider's sourceRewrites every resource in state from one provider address to the other and always saves a backup first.
terraform force-unlock LOCK_IDRelease a stuck state lockRemoves the lock with that ID from the state of the current configuration; infrastructure is not modified.
terraform force-unlock -force LOCK_IDUnlock without confirmationSkips the question that normally confirms the unlock.
terraform taint ADDRESSMark a resource as taintedDeprecated in favour of apply -replace; the next plan proposes replacing the tainted object.
terraform untaint ADDRESSRemove the tainted markerEdits only the state, for an object flagged as damaged that turned out to work correctly.

Importing existing infrastructure 7

CommandWhat it does
terraform import ADDRESS IDImport an existing resourceBinds the remote object with that provider-specific ID to a resource address in state; import each object only once.
terraform import module.foo.aws_instance.bar i-abcd1234Import into a moduleExample that places an EC2 instance in resource bar inside the module named foo.
terraform import 'aws_instance.baz[0]' i-abcd1234Import into a count instanceExample that targets the first instance of a resource configured with count.
terraform plan -generate-config-out=PATHGenerate config for import blocksExperimental: writes HCL for resources named in import blocks; the target has to be a file that is not there yet.
terraform querySearch existing infrastructureRuns the list blocks in .tfquery.hcl files and prints the matching remote resources so they can be imported.
terraform query -generate-config-out=PATHWrite import blocks for resultsSaves import and resource blocks for everything found; the target has to be a file that is not there yet.
terraform query -jsonQuery results as JSONCombined with -generate-config-out, the generated configuration lands in the JSON rather than in a file.

Workspaces 10

CommandWhat it does
terraform workspaceWorkspace subcommand groupContainer for the new, list, show, select and delete subcommands.
terraform workspace listList workspacesAn asterisk marks the workspace that is currently selected.
terraform workspace list -jsonWorkspace list as JSON
terraform workspace showShow the current workspace
terraform workspace new NAMECreate a workspaceFails when a workspace with that name is already present.
terraform workspace new -state=PATH NAMENew workspace from a state fileInitialises the fresh workspace with a copy of the state found at the given path.
terraform workspace select NAMESwitch workspaceLater operations use the chosen workspace, which must already exist.
terraform workspace select -or-create NAMESelect or create a workspaceMakes the workspace first when none of that name exists.
terraform workspace delete NAMEDelete a workspaceRefused when the workspace is the current one or still tracks resources.
terraform workspace delete -force NAMEForce-delete a workspaceDeletes even a workspace that tracks resources, which then live on unmanaged.

Providers and modules 12

CommandWhat it does
terraform providersShow required providersExplains where each provider requirement of the current configuration was detected.
terraform providers lockUpdate the dependency lock fileRecords provider versions and checksums from the origin registries without installing the providers.
terraform providers lock -platform=windows_amd64 -platform=darwin_amd64 -platform=linux_amd64Lock checksums for several platformsPre-populates the lock file for Windows, macOS and Linux so runs on those systems add no further checksums.
terraform providers lock -fs-mirror=DIRLock from a filesystem mirrorFor in-house providers: takes the packages from a local directory, not from their registry.
terraform providers lock -net-mirror=URLLock from a network mirrorFetches package data from a mirror service at that base URL rather than the registry.
terraform providers mirror TARGET-DIRMirror providers to a directoryDownloads every required provider into a local folder laid out as a filesystem mirror, for networks without registry access.
terraform providers mirror -platform=OS_ARCH TARGET-DIRMirror for another platformOtherwise only packages for the machine running the command are fetched; repeat the flag per target system.
terraform providers schema -jsonDump provider schemasPrints the detailed schemas of the providers the configuration uses; the -json flag is mandatory.
terraform getDownload modulesFetches the modules declared in the root module into the .terraform subdirectory.
terraform get -updateUpdate downloaded modulesModules that are already present are looked up again and replaced by newer releases where they exist.
terraform modulesList declared modulesShows each module's key, source and version; needs Terraform v1.10.0 or later.
terraform modules -jsonModule list as JSON

Testing and console 11

CommandWhat it does
terraform testRun module testsExecutes the test files in the current directory and the tests directory; it creates real infrastructure, then tries to destroy it.
terraform test -filter=TESTFILERun selected test filesLimits the run to the named file; repeat the option to add more files.
terraform test -test-directory=PATHChange the test directoryPoints the command at a folder other than the default, tests.
terraform test -verboseShow plan or state per runPrints the plan or the state of each run block while the tests execute.
terraform test -jsonTest results as JSON
terraform test -junit-xml=PATHWrite a JUnit XML reportStores the report at a relative or absolute path; it cannot be combined with -cloud-run.
terraform test -cloud-run=SOURCERun tests on HCP TerraformExecutes remotely for a module from a private registry, named by its source address.
terraform consoleOpen the expression consoleInteractive prompt for trying expressions and functions against the current state; type exit to leave.
terraform console -planConsole against a new planEvaluates expressions against the planned state, to inspect changes that are not applied yet.
terraform console -scope='module.child'Console inside a child moduleMoves the evaluation scope from the root module to the module address given.
echo 'split(",", "foo,bar,baz")' | terraform consoleEvaluate an expression from a scriptPipes newline-separated expressions into the console; only the result of the last one is printed.

Automation and environment variables 17

Arguments from TF_CLI_ARGS are inserted after the subcommand and before the flags typed on the command line, so the typed flags take precedence.

CommandWhat it does
terraform -chdir=DIR SUBCOMMANDRun from another directoryGlobal option placed in front of the subcommand; Terraform then reads and writes its files in DIR.
terraform apply -input=falseDisable interactive promptsBlocks the approval prompt as well, so apply fails unless approval comes another way.
terraform apply -jsonStream apply output as JSONEmits one JSON message per line and needs -auto-approve or a saved plan.
terraform plan -detailed-exitcodeExit code reports pending changesExit status 0 means no changes, 1 an error and 2 that the plan contains changes.
terraform plan -no-colorDisable coloured outputFor logs and systems that cannot render terminal formatting sequences.
export TF_LOG=traceEnable debug loggingSends detailed logs to stderr; unset the variable or set it to off to stop.
export TF_LOG_PATH=./terraform.logWrite logs to a fileOnly takes effect while TF_LOG is switched on too.
export TF_INPUT=0Disable prompts everywhereMakes every command behave as though -input=false had been passed; the value false works too.
TF_CLI_ARGSDefault arguments for all commandsIts value is inserted right after the subcommand, so flags typed on the command line still win.
TF_CLI_ARGS_plan="-refresh=false"Default arguments for one commandTF_CLI_ARGS_ plus a command name limits the extra arguments to that command, here plan.
TF_DATA_DIRMove the .terraform data directoryHas to be identical for every command from init onward, or providers and modules will not be found.
export TF_WORKSPACE=your_workspaceSelect a workspace by variableTakes the place of workspace select; recommended only for non-interactive runs.
TF_IN_AUTOMATIONMark a run as automatedOnce it holds a value, the output stops suggesting which command to run next; the change is cosmetic.
export TF_CLI_CONFIG_FILE="$HOME/.terraformrc-custom"Use another CLI config fileSupersedes TERRAFORM_CONFIG, an older name that is now deprecated.
TF_PLUGIN_CACHE_DIRSet the provider plugin cacheDoes the same job as plugin_cache_dir in the CLI configuration file, without editing that file.
export TF_REGISTRY_CLIENT_TIMEOUT=15Raise the registry timeoutRequests to the remote registry normally time out after 10 seconds.
CHECKPOINT_DISABLETurn off update checksOnce set, Terraform no longer asks HashiCorp Checkpoint about new versions and security bulletins.

Help, version and login 12

CommandWhat it does
terraform -helpList all commandsPrints the main workflow commands first, then the rest, followed by the global options.
terraform validate -helpHelp for one subcommandAdding -help to any subcommand prints its usage and options; validate is the example here.
terraform -versionPrint the versionA global option that does the same as the version subcommand.
terraform versionShow Terraform and provider versionsAlso names the platform and reports the upgrade and security check unless that check is disabled.
terraform version -jsonVersion details as JSONThe JSON object leaves out upgrade and security information.
terraform -install-autocompleteInstall shell tab completionAdds completion for command names to the bash or zsh profile; restart the shell afterwards.
terraform -uninstall-autocompleteRemove shell tab completionTakes the completion hook out of the shell profile, provided it was not edited by hand.
terraform loginSign in to HCP TerraformOpens a browser to obtain an API token for app.terraform.io and stores it locally; interactive use only.
terraform login HOSTNAMELog in to another hostFor Terraform Enterprise or any other host that offers Terraform services.
terraform logoutRemove saved credentialsDeletes the token from local storage only; it stays valid on the server until revoked.
terraform metadata functions -jsonList function signaturesPrints a JSON description of every function the Terraform language offers.
terraform stacksManage Terraform StacksEntry point for the Stacks commands, among them init, validate, create and list.

Notes

The loop

terraform init downloads providers and modules and configures the backend; run it after cloning and after adding a provider. terraform fmt and terraform validate tidy and type-check the configuration without touching infrastructure, and belong in CI. terraform plan computes the changes and prints them — read every line, because a resource marked for replacement is destroyed and created again — and terraform apply executes them after a confirmation; plan -out=file then apply file guarantees the applied change is the one reviewed. terraform destroy removes everything the configuration manages.

State

The state file maps configuration to real resources. terraform state list shows what Terraform believes it manages, and state show prints one resource's attributes. terraform import ADDRESS ID brings an existing resource under management by adding it to state — write the configuration block first, import, then plan until the diff is empty; an import block in the configuration does the same job during plan and apply. terraform output prints output values, with -json for scripts. Never edit the state file by hand; use the state subcommands, which write a backup before they change anything.

Workspaces and remote state

terraform workspace list shows workspaces, which give one configuration several independent states (dev, staging, prod) in the same backend; workspace select switches. For a team, a remote backend with locking (S3 with its lock file, HCP Terraform, GCS) is the first thing to configure, because two people applying against local state is how resources get orphaned. The older DynamoDB-based locking of the S3 backend is deprecated.

Questions

What is the Terraform workflow?

The basic workflow is: terraform init (initialize) → terraform plan (preview) → terraform apply (execute) → terraform destroy (cleanup).

What does terraform plan do?

terraform plan creates an execution plan showing what changes will be made to your infrastructure without actually applying them.

How do I import existing resources into Terraform?

Write the resource block, then run terraform import ADDRESS ID, where ID is the identifier the provider expects, such as an EC2 instance ID. An import block in the configuration does the same during plan and apply, and terraform plan -generate-config-out=PATH can draft the resource block for it.

How do I format Terraform files?

terraform fmt rewrites the configuration files in the current directory to the canonical style. Add terraform fmt -recursive to include subdirectories, or run terraform fmt -check in CI, which changes nothing and exits non-zero when a file needs formatting.

What replaced terraform taint and terraform refresh?

Both commands are deprecated. Instead of taint, run apply with the -replace option, for example terraform apply -replace="aws_instance.example[0]". Instead of refresh, run terraform apply -refresh-only, which shows the detected changes and asks before writing them to the state.

How do I make sure apply runs exactly the plan I reviewed?

Save the plan with terraform plan -out=PATH, read it with terraform show FILE, then give the same file to apply (terraform apply PLAN). A saved plan is applied without a confirmation prompt, and no further planning options can be added at that point.

Sources and checks

38 more source pages

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.