Terraform has a small command surface — about two dozen commands — but they interact in ways that are not obvious until something goes wrong. The famous cycle is only four commands long: init, plan, apply, destroy. The rest of the CLI exists for the moments around that cycle: formatting and validating configuration, passing variables, managing state, importing resources that already exist, and recovering when a lock or a drifted resource blocks you.
This cheat sheet groups every command you realistically need by the job it does, with the flags that matter, a short explanation of what each one does, and the mistake teams make with it most often. Commands are current for Terraform 1.17.3, verified 5 Dec 2026, and the HashiCorp CLI command reference is the authority when a flag behaves differently than described here. If you are new to infrastructure as code, start with our Terraform tutorial for beginners for the full worked example, then keep this page as the reference you come back to.
The Core Workflow: init, plan, apply, destroy
Every Terraform session follows the same cycle, and the order matters. You initialize the working directory, preview the changes, approve them, and only then does anything touch real infrastructure. Skipping the preview is the single most common Terraform mistake, and it is the one that deletes production resources.
terraform init
terraform init -upgrade
terraform init -backend-config=prod.hcl
terraform init -migrate-state
terraform init -reconfigure
terraform init -input=false
terraform plan
terraform plan -out=tfplan
terraform plan -refresh-only
terraform plan -destroy
terraform plan -target=aws_instance.web
terraform init prepares the working directory: it downloads the provider plugins your configuration needs, installs modules, and configures the backend where state will live. Run it first in every new or changed working directory, and run it again whenever the configuration changes providers, modules, or backend settings — Terraform will tell you when initialization is required, and it will refuse to plan until you do. -upgrade allows newer provider versions within the constraints you declared, which is how you pick up a provider update deliberately rather than by accident. -backend-config supplies backend values from a file, so credentials and bucket names stay out of the configuration itself. -migrate-state moves state when the backend changed, and -reconfigure reinitializes the backend while ignoring any existing configuration — the right flag when you are pointing an existing directory at a new backend.
terraform plan computes the difference between your configuration, the state file, and the real infrastructure, and shows it without changing anything. Read the symbols: + means create, - destroy, ~ update in place, - /+ destroy then recreate, and <= means read, for a data source. -out=tfplan saves the plan to a file so that the later apply executes exactly the plan you reviewed — in a pipeline, always save the plan and apply the file, never re-plan at apply time, because the world can change between the two. -refresh-only shows drift — changes made outside Terraform — without proposing configuration changes. -target narrows the plan to one resource, which is useful for a surgical fix and dangerous as a habit, because a targeted plan can leave the rest of the infrastructure in an inconsistent state.
terraform apply
terraform apply tfplan
terraform apply -auto-approve
terraform apply -replace=aws_instance.web
terraform apply -var "region=us-east-1"
terraform apply -parallelism=5
terraform apply -lock-timeout=5m
terraform destroy
terraform destroy -target=aws_instance.web
terraform apply without arguments plans again and asks for confirmation; terraform apply tfplan executes a saved plan with no prompt, because the approval already happened when the plan was reviewed. -auto-approve skips the confirmation prompt entirely — the right flag in a CI pipeline that has already reviewed a saved plan, and a dangerous flag on a human’s laptop, where it turns a typo into an outage. -replace forces one resource to be destroyed and recreated, which is the modern way to rebuild a misbehaving instance; it replaced the older terraform taint command, which still exists but is deprecated. -parallelism limits how many resources Terraform changes at once — lower it when a provider throttles your API calls. -lock-timeout tells Terraform how long to wait for the state lock before giving up, which matters when a colleague’s apply is still running.
Terraform 1.17 added one more planning flag worth knowing: -minimal-refresh. A normal plan asks the cloud about every object in the state before computing the difference, which is thorough and slow on large infrastructures. With -minimal-refresh, Terraform only refreshes the resources that have proposed changes, so plans run much faster — at the cost of possibly missing drift in resources the plan does not touch. Use it when you are iterating on a change in a large configuration and you already know the rest of the infrastructure is untouched; do not use it for a final pre-apply review, where a full refresh is what catches surprises.
terraform destroy removes everything the configuration manages, after a confirmation prompt. It is the command to run with the most care in the entire CLI: there is no undo, and a destroy in the wrong directory removes the wrong infrastructure. Always check terraform workspace show and the backend configuration before destroying, and prefer terraform plan -destroy first so you see the full list of what will go. The mistake that costs teams real money is running destroy against a directory whose backend points at production while believing it points at a test environment.
Writing and Validating Configuration
Three commands keep your configuration honest before it ever reaches a plan, and none of them touches infrastructure. They are cheap, fast, and should run on every save and every commit — in your editor, in a pre-commit hook, and in CI. The exam and interview favorite is the trap pair: fmt formats, validate validates, and neither checks anything against real cloud APIs.
terraform fmt
terraform fmt -recursive
terraform fmt -check
terraform fmt -diff
terraform validate
terraform validate -backend=false
terraform console
terraform version
terraform -help
terraform plan -help
terraform fmt rewrites your .tf files to the canonical HCL style — consistent indentation, aligned equals signs, sorted blocks. Run it before every commit, or better, let your editor run it on save. -recursive formats subdirectories too, which is what you want in a repository with modules. -check reports files that are not formatted without changing them, which is the CI form: the pipeline fails if formatting is off, and the developer fixes it locally. -diff shows the formatting changes without applying them, useful when you want to see what fmt would do to a file you did not write.
terraform validate checks syntax and internal consistency: are the resource references valid, are required arguments present, do the types line up. It does not contact any cloud API, so it cannot catch a wrong AMI ID or a non-existent subnet — that is what plan is for. -backend=false skips backend validation, which is useful when you are validating a module in isolation, before any backend exists. terraform console is an interactive REPL for evaluating expressions: type var.region or a function call and see the result immediately, which is the fastest way to debug a complex expression without running a full plan. terraform version prints the CLI version and the provider versions in use, and every command accepts -help for its own flag list — terraform plan -help is faster than searching the web for a flag you half remember.
Variables and Outputs
Variables are how one configuration serves many environments: the same code, different region, different instance size, different environment name. Terraform variables come from several sources, and the order they override each other is the part people get wrong — so learn the precedence once and you will stop being surprised by it.
terraform plan -var "instance_type=t3.small"
terraform plan -var-file="prod.tfvars"
terraform plan -var-file="common.tfvars" -var-file="prod.tfvars"
terraform apply -var "environment=staging"
TF_VAR_region=us-east-1 terraform plan
terraform output
terraform output -json
terraform output instance_ip
terraform output -raw db_password
-var sets one variable on the command line, good for a single override in a script. -var-file loads a whole file of values, and when you pass more than one, later files override earlier ones — so put the shared values first and the environment-specific file last. A terraform.tfvars file in the working directory loads automatically, which is convenient and also the reason secrets should never live in it: anything in a .tfvars file is easy to commit by accident, so keep secrets in environment variables with the TF_VAR_ prefix, which Terraform reads automatically.
terraform output prints the outputs the configuration declares — IP addresses, bucket names, connection strings — and -json prints them in a format scripts can consume, which is how one Terraform configuration feeds values into the next tool in a pipeline. -raw prints a single string output without quotes, which is what you want when piping a value into another command. Mark sensitive outputs as sensitive = true in the configuration: Terraform will hide them from normal output, though they still exist in the state file, so treat state as sensitive data and keep it encrypted and access-controlled. The common mistake is passing a variable on the command line in CI and leaving it visible in the build log — use TF_VAR_ variables or a variables file instead.
One more rule worth knowing: a file named terraform.tfvars in the working directory loads automatically, and any file ending in .auto.tfvars does too. That is convenient for shared defaults, and it is also how secrets leak into version control — a .tfvars file committed by accident is one of the most common ways credentials end up in a repository. Keep *.tfvars out of version control unless the file contains only non-sensitive values, and mark any variable that holds a secret as sensitive = true so Terraform hides it from plan output and logs.
One more variable rule worth memorizing: a variable with no default is required, and Terraform will prompt for it interactively if you do not supply it. That prompt is what breaks unattended pipelines, so either give every variable a sensible default, supply all values in CI, or pass -input=false so Terraform fails loudly instead of waiting forever for input that will never come.
State Management
State is the file Terraform uses to remember what it created: which resources exist, what their IDs are, and what attributes they have. It is the mapping between your configuration and the real world, and it is the most sensitive and most misunderstood part of Terraform. The rule that governs all state commands is simple: never edit the state file by hand, and never let two processes change it at once. Our Terraform state guide explains backends and locking in depth; this section is the command reference for the same ideas.
terraform state list
terraform state show aws_instance.web
terraform state mv aws_instance.old aws_instance.new
terraform state rm aws_instance.web
terraform state pull
terraform state push backup.tfstate
terraform state replace-provider registry.terraform.io/hashicorp/aws registry.terraform.io/hashicorp/aws
terraform refresh
terraform state list shows every resource in the state, which is the first command to run when you are unsure what Terraform thinks it manages. terraform state show prints the full recorded attributes of one resource — its ID, its IP address, every argument Terraform stored — which is how you check what Terraform believes without logging into the cloud console. terraform state mv renames a resource in the state, which is what you do after renaming a resource in your configuration so Terraform does not destroy the old one and create a new one. terraform state rm removes a resource from state without destroying it: Terraform stops managing it, and the real resource keeps running, orphaned, until someone deals with it. That is a useful escape hatch and a dangerous one, so use it deliberately.
terraform state pull downloads the current state to standard output, and terraform state push uploads a state file — the pair you use to inspect or repair state, and to restore from a backup. terraform state replace-provider rewrites the provider address recorded in state, which you need when a provider moves registry or namespace. terraform refresh reconciles state with the real world, but note that modern Terraform prefers terraform plan -refresh-only, which shows you the drift before it writes anything. State locking is what makes all of this safe in a team: with an S3 backend, set use_lockfile = true so concurrent applies block instead of corrupting state. If an apply is interrupted and the lock stays held, check that no apply is actually running before you force-unlock — unlocking a live apply is how state gets corrupted.
terraform force-unlock 3e887ab-1234-5678-90ab-cdef12345678
terraform state list -id=aws_instance.web
terraform providers
terraform providers schema -json
terraform providers lock
terraform force-unlock takes a lock ID, printed in the error message of the blocked command — never guess the ID, and never force-unlock without confirming the other process is really dead. terraform providers lists the providers a configuration uses and their versions, providers schema -json dumps the full schema for tooling, and providers lock writes provider hashes into the lock file so every machine installs the same provider builds. The provider lock file, .terraform.lock.hcl, should be committed to version control: without it, two machines can install different provider versions and produce different plans from the same code.
Workspaces and Environments
Workspaces let one configuration manage several copies of the same infrastructure — a development copy and a staging copy, for example — by keeping a separate state file for each. They are cheap and easy, which is also why they are overused: a workspace is not an environment strategy, and the moment your environments need different variables, different sizes, or different modules, separate directories or separate configurations are the better design. Our Terraform workspaces guide covers that decision in full; here are the commands.
terraform workspace list
terraform workspace show
terraform workspace new staging
terraform workspace select staging
terraform workspace select default
terraform workspace delete staging
terraform workspace new prod -state=prod.tfstate
terraform workspace list shows all workspaces with an asterisk on the active one, and workspace show prints just the active name — put it in a deployment script’s output so the log always says which environment the command ran against. workspace new creates a workspace and switches to it; workspace select switches between existing ones. The default workspace is always called default, and every configuration starts there. workspace delete removes a workspace and its state, but only if the workspace is empty or you confirm — Terraform refuses to delete a workspace that still manages resources, which is the safety net that stops you deleting an environment by accident.
The classic workspace mistake is running a command in the wrong workspace. There is no prompt and no warning: terraform apply in the staging workspace applies to staging, and the same command in the default workspace applies to whatever the default workspace manages. Make the workspace visible in your shell prompt, or print terraform workspace show at the top of every deployment script, so the environment is always in front of you. The second mistake is using workspaces to paper over real differences: if staging needs a smaller instance and production needs a bigger one, that is a variable, and it belongs in a .tfvars file per workspace, not in a conditional buried in the configuration.
Import, Targeting and Replacement
Not all infrastructure starts in Terraform. A database created by hand in the console, a bucket from before the team adopted infrastructure as code, a resource created by another tool — import is how you bring those under Terraform management without recreating them. Targeting and replacement are the surgical tools for fixing one resource without touching the rest.
terraform import aws_instance.web i-0123456789abcdef0
terraform import aws_s3_bucket.assets my-company-assets
terraform plan -generate-config-out=generated.tf
terraform apply -target=aws_instance.web
terraform apply -replace=aws_instance.web
terraform plan -refresh=false
terraform apply -refresh=false
terraform taint aws_instance.web
terraform import takes a resource address and the real world’s ID for it, and records the resource in state. It does not generate configuration — after an import, you must write the resource block yourself, and the next plan will show you the difference between what you wrote and what actually exists. The modern alternative is an import block in the configuration, which is reviewable and repeatable: declare the import, run plan -generate-config-out, and Terraform writes a first draft of the configuration for you to clean up. Either way, import is a two-step job — state first, configuration second — and the mistake is doing the first step and forgetting the second, leaving a resource in state with no configuration to manage it.
-target limits an apply to one resource and its dependencies. It is the right tool for an emergency fix — one instance is misbehaving and you need to recreate it now — and the wrong tool for routine work, because a targeted apply can leave the rest of your infrastructure out of sync with the configuration, and the next full apply will then show unexpected changes. -replace marks one resource for destroy and recreate, which is the current replacement for the deprecated terraform taint: taint still works, but it only marks the resource, while -replace does the same thing in the apply itself, and it is what the Terraform Associate exam expects you to know. -refresh=false skips the step where Terraform asks the cloud about every resource before planning, which makes large plans faster — but it also means Terraform is planning from stale state, so use it only when you know nothing changed outside Terraform.
Providers, Modules and Troubleshooting
Providers are the plugins that talk to clouds and services, and modules are reusable packages of configuration. The commands in this section answer the questions you ask when a plan fails for reasons that have nothing to do with your code: the wrong provider version, a missing module, a lock held by a dead process, or a resource that already exists.
terraform get
terraform get -update
terraform init -get=false
terraform providers mirror ./mirror
terraform login
terraform logout
terraform version
terraform version -json
terraform get downloads modules into the working directory, and -update re-downloads them even if they are already present — the flag to use when a module’s source changed and your local copy is stale. init -get=false skips module installation, which is useful when you only want to update providers. terraform providers mirror builds a local mirror of provider packages for air-gapped or locked-down environments, where the machine running Terraform cannot reach the registry. terraform login and logout manage credentials for Terraform Cloud and the registry: login stores a token for publishing modules and running remote operations, and logout removes it. terraform version -json prints version information in a machine-readable format for scripts.
When something fails, work through the same sequence every time. First, read the error message in full — Terraform’s errors are unusually specific, and they usually name the file, the line, and the fix. Then check the basics: terraform version for a version mismatch, terraform init for a missing provider or module, terraform workspace show for the wrong environment. Then check the common failures:
terraform init
terraform workspace show
terraform plan
terraform state list
terraform providers lock -platform=linux_amd64
“Provider produced inconsistent result” usually means the provider version and the state disagree — run terraform init -upgrade or pin the provider version explicitly. “Error acquiring the state lock” means another apply is running or a previous one died holding the lock: confirm no process is running, then force-unlock with the lock ID from the error. “Resource already exists” means the real resource exists but is not in state — import it instead of trying to create it again. “Inconsistent dependency lock file” means the lock file does not match the configuration: run terraform providers lock to regenerate it, and commit the result. The Terraform language documentation is the reference for the configuration side of every one of these errors, and it is worth reading the page for the resource type you are fighting before assuming the tool is wrong.
Frequently Asked Questions
What is the difference between terraform plan and terraform apply?
terraform plan previews the changes Terraform would make, without changing anything. terraform apply executes those changes against real infrastructure. Always plan first, read the output, and then apply — in a pipeline, save the plan with -out and apply the saved file so the apply is exactly what you reviewed.
Do I need to run terraform init every time?
No, only when the working directory is new or when providers, modules, or backend settings change. Terraform tells you when initialization is required and refuses to plan until you run it. Re-running init on an initialized directory is harmless, so when in doubt, run it — it is cheaper than debugging a plan that failed for a missing provider.
What is the difference between terraform fmt and terraform validate?
terraform fmt reformats your files to canonical HCL style; terraform validate checks syntax and internal consistency. Neither contacts a cloud API, so neither can catch a wrong AMI ID or a non-existent subnet — that is what plan is for. Run both on every commit, and enforce fmt -check in CI.
Is terraform taint still used?
It still exists, but it is deprecated. The modern replacement is terraform apply -replace=address, which forces a resource to be destroyed and recreated in the same apply. Learn -replace and use it; the Terraform Associate exam tests the distinction.
What should I do when Terraform says the state is locked?
First, check whether another apply is genuinely running — in CI, look at the pipeline; on a shared machine, ask the team. If no apply is running and the lock is stale from an interrupted process, run terraform force-unlock with the lock ID from the error message. Never force-unlock a live apply: two processes writing state at once is how state gets corrupted.
Conclusion
Terraform’s CLI rewards the engineer who treats it as a workflow, not a bag of commands. Initialize, plan, review, apply — and then use the rest of the commands for the jobs around that cycle: formatting and validating before you plan, passing variables cleanly, managing state carefully, and importing or replacing one resource at a time when reality diverges from the configuration.
The fastest way to make these commands stick is to use them on a real project: build a small environment, change it, drift it by hand in the console, and bring it back with plan -refresh-only and apply. That loop — change, drift, detect, correct — is the daily work of infrastructure as code, and these are the commands that carry it.



