You drive Terraform from the command line, and about ten commands are enough
day to day. This reference page presents each of them with its essential
options and examples: from terraform init, the first one to run, to
terraform state to inspect what Terraform has recorded.
What you will learn
- The daily cycle commands:
init,fmt,validate,plan,apply,destroy - The key options:
-out,-target,-var,-var-file,-auto-approve - Inspecting the state:
state list,state show,show,output - Debugging expressions: using
terraform consoleas an interactive REPL
Display a command's help
Each command describes its options in the terminal, without going through the online documentation:
# General helpterraform -help
# Help on a specific commandterraform init -helpterraform plan -helpterraform init
Initializes the project: downloads the providers (the plugins that talk to platforms) and configures the backend (the place where the state is stored, the file where Terraform records what it created). Terraform refuses to work until this command has been run in the directory.
terraform initUseful options:
| Option | Effect |
|---|---|
-upgrade | Updates the providers to the latest compatible version |
-reconfigure | Reinitializes the backend without carrying the state over |
-migrate-state | Copies the state from the old backend to the new one |
-backend=false | Init without configuring a backend |
# Update the providersterraform init -upgrade
# After a backend change: move the state to the new oneterraform init -migrate-state-migrate-state asks for confirmation before copying the existing state to the
new backend: it is the command to use when the state must follow the project.
In a script, where nobody can answer, -force-copy answers "yes" to these
questions and also enables -migrate-state.
-reconfigure starts again from the new backend without copying anything:
Terraform no longer sees the old state, and the next plan proposes to
recreate everything. Use it only to start from scratch on purpose. Backends
are covered in the guide on
Terraform backends (in French).
terraform validate
Checks the syntax and the logical consistency of the configuration, for example a reference to a resource that does not exist. It does not contact the providers' APIs: nothing is read or created on their side.
terraform validateWhen the configuration is correct, the command answers:
Success! The configuration is valid.Options:
| Option | Effect |
|---|---|
-json | Result in JSON (ideal for CI/CD) |
-no-color | Disables colors |
jq is a separate tool, to be installed, that filters JSON. With it, the CI
reads the result directly:
# For the CIterraform validate -json | jq '.valid'On a valid configuration, the command prints true.
terraform fmt
Reformats the .tf files according to the Terraform canonical format. This
format can change slightly between minor versions.
# Reformat all the files in the current directoryterraform fmt
# Reformat recursively (subdirectories included)terraform fmt -recursive
# Check without modifying (ideal for CI)terraform fmt -check -recursiveOn files that are already correctly formatted, fmt -check prints nothing and
returns exit code 0 (check it with echo $?). Otherwise, it lists the files to
reformat and returns a non-zero code.
terraform plan
Computes and displays the changes without applying them: this is the step where you review what Terraform is about to do.
terraform planEssential options:
| Option | Effect |
|---|---|
-out=FILE | Saves the plan, which apply then runs as is |
-var="name=value" | Passes a variable on the command line |
-var-file=FILE | Loads a variables file |
-target=RESOURCE | Limits the plan to a specific resource |
-destroy | Plans a complete destruction |
-refresh=false | Does not refresh the state from the API |
-json | Machine-readable output (for automation and CI integrations, not for human reading) |
# Targeted plan (for debugging)terraform plan -target=libvirt_domain.vm
# Destroy planterraform plan -destroy
# Saved plan for a deterministic applyterraform plan -out=tfplan && terraform apply tfplanA saved plan contains the configuration values in clear text, passwords
included. Do not commit it, and delete it after the apply.
terraform apply
Applies the changes. By default, it asks for confirmation before acting.
terraform applyEssential options:
| Option | Effect |
|---|---|
-auto-approve | Applies without confirmation |
-var="name=value" | Variable on the command line |
-var-file=FILE | Variables file |
-target=RESOURCE | Applies only one resource |
-replace=RESOURCE | Forces the recreation of a resource |
-refresh=false | Does not query the API before apply |
# Apply without confirmation (CI/CD)terraform apply -auto-approve
# Force the recreation of a VMterraform apply -replace=libvirt_domain.vmterraform destroy
Deletes all the managed resources. Without -auto-approve, Terraform lists what
it is going to destroy and waits for you to type yes.
terraform destroyterraform destroy -auto-approveEquivalent to:
terraform apply -destroy -auto-approveTo destroy a single resource:
terraform destroy -target=libvirt_volume.diskterraform output
Displays the values of the outputs defined in outputs.tf.
# All the outputsterraform output
# One specific outputterraform output vm_name
# In JSON (for scripts)terraform output -jsonterraform output -json vm_nameWith the two outputs of the first infrastructure, the first two commands display (tested with Terraform 1.17.2):
disk_path = "/var/lib/libvirt/images/lab-vm.qcow2"vm_name = "lab-vm"
"lab-vm"Terraform puts strings between quotes when you ask for a single output; for a
script, terraform output -raw vm_name removes them.
terraform show
Displays a state or a plan file in a readable way.
# Display the latest state snapshotterraform show
# Display a saved plan fileterraform show tfplan
# In JSON (careful: sensitive values are displayed in clear text)terraform show -json | jq .terraform show -json tfplanterraform state
Subcommands to inspect and manipulate the state: the list of tracked resources, the detail of one of them, and the operations that modify the state without touching the infrastructure.
# List the resources in the stateterraform state list
# Display a specific resourceterraform state show libvirt_domain.vm
# Remove a resource from the state (without destroying it)terraform state rm libvirt_volume.disk
# Rename a resource in the stateterraform state mv libvirt_domain.vm libvirt_domain.serveurOn the first infrastructure project, terraform state list displays:
libvirt_domain.vmlibvirt_volume.diskThere is one line per tracked resource, in the form type.name. A resource
missing from this list is not managed by Terraform.
state mv modifies the state immediately, without touching the infrastructure:
the existing VM stays in place, only its name in the state changes. For a
simple rename, you can write a moved block in the code instead, a declaration
that says "this resource is now called this" (Terraform 1.1 or later). The
result is the same, but the plan shows the change and the state is only
modified at apply. The guide on
import, moved and removed in OpenTofu (in French)
details this block, which Terraform also accepts.
terraform console
A REPL (a prompt where you type an expression and read its result right away)
to test Terraform expressions without modifying the infrastructure. The console
can read the values present in the state, and it takes a lock on the state
for the whole session. exit or Ctrl+D closes it.
terraform consoleThe last expression below reads var.environment. This variable must be
declared in the project, otherwise the console answers Reference to undeclared input variable:
variable "environment" { type = string default = "dev"}Here is what four expressions return (tested on Debian 13 with Terraform 1.17.2):
> max(5, 12, 9)12
> format("vm-%03d", 7)"vm-007"
> length(["a", "b", "c"])3
> var.environment == "prod" ? "large" : "small""small"The console is for trying out a function or debugging an expression before writing it in the code.
terraform graph
Generates a representation of a configuration or an execution plan in DOT format
(the Graphviz format). By default, it displays a simplified view of the
dependencies between resources and data sources. The dot command is part of
Graphviz, to be installed separately.
terraform graph | dot -Tsvg > graph.svgPut it into practice
The starting configuration has three defects: a file outside the canonical format, an orphan reference (a reference to a resource that does not exist) that makes validate fail, and missing outputs. You fix these defects without changing what the configuration produces, then you recompute an expression with the console, outside the state. The validation checks these fixes.
Key points
initis always the first step in a new project.fmt -checkin CI rejects code that is not in the canonical format.plan -out=tfplanthenapply tfplanapplies exactly the plan you reviewed, which suits production.consolelets you test an HCL expression without changing anything.- Use
state mvandstate rmonly with a backup at hand.
Knowledge check
This check reviews the whole Discover Terraform module, not only this page: the workflow, the CLI, installation and the structure of a project. Each question links to the lesson that justifies the answer.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
A new full quiz with random questions
Work again only on the questions you missed