Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

The Terraform CLI: everyday commands

12 min read
Improve this page

Logo Terraform

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 console as an interactive REPL

Display a command's help

Each command describes its options in the terminal, without going through the online documentation:

Terminal window
# General help
terraform -help
# Help on a specific command
terraform init -help
terraform plan -help

terraform 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.

Terminal window
terraform init

Useful options:

OptionEffect
-upgradeUpdates the providers to the latest compatible version
-reconfigureReinitializes the backend without carrying the state over
-migrate-stateCopies the state from the old backend to the new one
-backend=falseInit without configuring a backend
Terminal window
# Update the providers
terraform init -upgrade
# After a backend change: move the state to the new one
terraform 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.

Terminal window
terraform validate

When the configuration is correct, the command answers:

Success! The configuration is valid.

Options:

OptionEffect
-jsonResult in JSON (ideal for CI/CD)
-no-colorDisables colors

jq is a separate tool, to be installed, that filters JSON. With it, the CI reads the result directly:

Terminal window
# For the CI
terraform 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.

Terminal window
# Reformat all the files in the current directory
terraform fmt
# Reformat recursively (subdirectories included)
terraform fmt -recursive
# Check without modifying (ideal for CI)
terraform fmt -check -recursive

On 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.

Terminal window
terraform plan

Essential options:

OptionEffect
-out=FILESaves the plan, which apply then runs as is
-var="name=value"Passes a variable on the command line
-var-file=FILELoads a variables file
-target=RESOURCELimits the plan to a specific resource
-destroyPlans a complete destruction
-refresh=falseDoes not refresh the state from the API
-jsonMachine-readable output (for automation and CI integrations, not for human reading)
Terminal window
# Targeted plan (for debugging)
terraform plan -target=libvirt_domain.vm
# Destroy plan
terraform plan -destroy
# Saved plan for a deterministic apply
terraform plan -out=tfplan && terraform apply tfplan

A 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.

Terminal window
terraform apply

Essential options:

OptionEffect
-auto-approveApplies without confirmation
-var="name=value"Variable on the command line
-var-file=FILEVariables file
-target=RESOURCEApplies only one resource
-replace=RESOURCEForces the recreation of a resource
-refresh=falseDoes not query the API before apply
Terminal window
# Apply without confirmation (CI/CD)
terraform apply -auto-approve
# Force the recreation of a VM
terraform apply -replace=libvirt_domain.vm

terraform destroy

Deletes all the managed resources. Without -auto-approve, Terraform lists what it is going to destroy and waits for you to type yes.

Terminal window
terraform destroy
terraform destroy -auto-approve

Equivalent to:

Terminal window
terraform apply -destroy -auto-approve

To destroy a single resource:

Terminal window
terraform destroy -target=libvirt_volume.disk

terraform output

Displays the values of the outputs defined in outputs.tf.

Terminal window
# All the outputs
terraform output
# One specific output
terraform output vm_name
# In JSON (for scripts)
terraform output -json
terraform output -json vm_name

With 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.

Terminal window
# Display the latest state snapshot
terraform show
# Display a saved plan file
terraform show tfplan
# In JSON (careful: sensitive values are displayed in clear text)
terraform show -json | jq .
terraform show -json tfplan

terraform 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.

Terminal window
# List the resources in the state
terraform state list
# Display a specific resource
terraform 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 state
terraform state mv libvirt_domain.vm libvirt_domain.serveur

On the first infrastructure project, terraform state list displays:

libvirt_domain.vm
libvirt_volume.disk

There 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.

Terminal window
terraform console

The 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.

Terminal window
terraform graph | dot -Tsvg > graph.svg

Put 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

  • init is always the first step in a new project.
  • fmt -check in CI rejects code that is not in the canonical format.
  • plan -out=tfplan then apply tfplan applies exactly the plan you reviewed, which suits production.
  • console lets you test an HCL expression without changing anything.
  • Use state mv and state rm only 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

8 questions
8 min
70% to pass

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