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

The Terraform workflow: init, plan, apply, destroy

24 min read
Improve this page

Logo Terraform

You run terraform apply and your infrastructure changes, but you do not know exactly what happened. Or worse: you applied without looking at the plan, and Terraform destroyed a resource that you wanted to keep.

The basic Terraform cycle fits in four commands: init, plan, apply and destroy, with validate added before the plan. The official core workflow from HashiCorp counts only three steps, Write, Plan and Apply: init prepares the directory and destroy is a complementary command. This cycle makes every change predictable: the plan shows what will change before anything is modified. Knowing how to read the +, - and ~ symbols of that plan is the basic skill for using Terraform without nasty surprises.

What you will learn

  • The role of each command: init, validate, plan, apply, destroy
  • Read a Terraform plan: interpret the +, -, ~ before applying
  • Prepare KVM/libvirt: the pool, the network and the disk image of the example
  • Run a complete cycle: from initialization to destruction on KVM/libvirt
  • The role of the state: what Terraform remembers between two apply runs, and why you must not delete it

Prerequisites

  • Terraform installed, in version 1.17.2 to get the outputs shown on this page (installation guide)
  • A Linux machine where KVM virtualization is available, with an account allowed to use sudo: the section "How do you prepare KVM for the example?", further down, installs libvirt, creates the storage pool and the default network, then places the Ubuntu 24.04 cloud image under ~/images/ubuntu-24.04-cloudimg.img, the path that the example uses

Without KVM, you can still observe a first cycle: the lab of the lesson What is Terraform? applies a local configuration, which does not need any virtual machine.

What does the complete cycle look like at a glance?

The diagram chains the five commands from top to bottom, from initialization to destruction. Look for the three commands that it links to the state file terraform.tfstate: plan reads it, apply writes it, and destroy reads it then rewrites it without the deleted resources.

Terraform cycle from top to bottom: init downloads the providers, validate checks the syntax, plan computes the changes, apply applies them, destroy deletes the resources; plan reads the terraform.tfstate file, apply writes it, and the delete command reads it then rewrites it.readswritesreads then rewritesterraform initdownloads the providers and initializes the projectterraform validatechecks the HCL syntax without calling the APIterraform plancomputes and shows the planned changesterraform applyapplies the changes and creates the infrastructureterraform destroydeletes every managed resourceterraform.tfstatestored stateTerraform commandcheck without calling the APIstate filenext commandreads or writes the state
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

The outputs of init, validate, plan and apply in the five following steps come from the example in the section Complete example on KVM/libvirt: two resources, a disk volume and a virtual machine. The output of destroy is not reproduced: step 5 gives the command that checks its effect. Read the steps first, then reproduce the example in order at the end.

Step 1, terraform init

terraform init is always the first command to run in a new project, or after adding a provider. It:

  • downloads the providers declared in the required_providers block (the plugins that connect Terraform to an API);
  • initializes the backend, the place where Terraform stores the state (a local file by default);
  • prepares the .terraform/ directory.
Terminal window
terraform init

Excerpt of the expected result (Terraform also prints a reminder about the lock file .terraform.lock.hcl):

Initializing the backend...
Initializing provider plugins...
- Finding dmacvicar/libvirt versions matching "~> 0.9.0"...
- Installing dmacvicar/libvirt v0.9.9...
- Installed dmacvicar/libvirt v0.9.9 (self-signed, key ID 0833E38C51E74D26)
Terraform has been successfully initialized!

Step 2, terraform validate

terraform validate checks that the configuration is syntactically valid and internally consistent. It does not contact the remote APIs of the providers and does not read the remote state, but it requires a directory that has already been initialized by terraform init.

Terminal window
terraform validate

Expected result:

Success! The configuration is valid.

In case of an error, for example a format argument placed at the top level of a volume while provider 0.9 expects it in target, Terraform prints the error in a frame:

╷
│ Error: Unsupported argument
│
│ on main.tf line 4, in resource "libvirt_volume" "disk":
│ 4: format = "qcow2"
│
│ An argument named "format" is not expected here.
╵

Run validate before every plan to catch typos and unknown attributes. If you do not want to configure the backend yet, run terraform init -backend=false first.

Step 3, terraform plan

terraform plan reads the current state of the remote objects through the providers, compares it with the configuration and the existing state, then computes the actions needed for the infrastructure to match the configuration.

Terminal window
terraform plan

Here is the plan of the complete example, before the first creation. It is an excerpt: it stops at the Changes to Outputs block, and Terraform then adds a note about the -out option. Each resource is preceded by a symbol: + creates, ~ changes in place, - deletes, and -/+ deletes then recreates.

Terraform used the selected providers to generate the following execution
plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# libvirt_domain.vm will be created
+ resource "libvirt_domain" "vm" {
+ devices = {
+ disks = [
+ {
+ driver = {
+ type = "qcow2"
}
+ source = {
+ file = {
+ file = (known after apply)
}
}
+ target = {
+ bus = "virtio"
+ dev = "vda"
}
},
]
+ interfaces = [
+ {
+ model = {
+ type = "virtio"
}
+ source = {
+ network = {
+ network = "default"
}
}
},
]
}
+ id = (known after apply)
+ memory = 512
+ memory_unit = "MiB"
+ name = "workflow-demo"
+ os = {
+ type = "hvm"
+ type_arch = "x86_64"
+ type_machine = "q35"
}
+ running = true
+ type = "kvm"
+ uuid = (known after apply)
+ vcpu = 1
}
# libvirt_volume.disk will be created
+ resource "libvirt_volume" "disk" {
+ allocation = (known after apply)
+ capacity = (known after apply)
+ create = {
+ content = {
+ url = "/home/ansible/images/ubuntu-24.04-cloudimg.img"
}
}
+ id = (known after apply)
+ key = (known after apply)
+ name = "workflow-demo.qcow2"
+ path = (known after apply)
+ physical = (known after apply)
+ pool = "default"
+ target = {
+ format = {
+ type = "qcow2"
}
+ path = (known after apply)
}
}
Plan: 2 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ vm_name = "workflow-demo"

Look first at the line Plan: 2 to add, 0 to change, 0 to destroy.: it announces two resources to create, none to change or delete. The detail above tells you which ones, and the + sign in front of libvirt_domain.vm and libvirt_volume.disk confirms that they are creations. (known after apply) marks a value that Terraform can only know after the creation, such as the identifier or the path of the volume. The path in url carries the name of the user who ran the plan: yours will be different. The Changes to Outputs block announces the vm_name value that will be displayed at the end of the apply.

How do you read the ~ and -/+ symbols?

A plan does not only make creations. Once the VM is created, change memory = 512 to memory = 768 in main.tf and run terraform plan again: Terraform shows an in-place change, without recreating the VM. Excerpt of the plan, after the two Refreshing state lines:

~ update in-place
Terraform will perform the following actions:
# libvirt_domain.vm will be updated in-place
~ resource "libvirt_domain" "vm" {
id = 1
~ memory = 512 -> 768
name = "workflow-demo"
# (7 unchanged attributes hidden)
}
Plan: 0 to add, 1 to change, 0 to destroy.

The ~ marks a changed resource, and the line 512 -> 768 gives the old then the new value. Attributes that do not move are hidden. Some arguments cannot be changed in place: replace the name of the workflow-demo domain with workflow-demo-2, and the plan announces a replacement. Excerpt (one line about memory is omitted):

# libvirt_domain.vm must be replaced
-/+ resource "libvirt_domain" "vm" {
~ id = 2 -> (known after apply)
~ name = "workflow-demo" -> "workflow-demo-2" # forces replacement
~ uuid = "a48872c7-7c08-4fd5-9664-47eb27044782" -> (known after apply)
# (6 unchanged attributes hidden)
}
Plan: 1 to add, 0 to change, 1 to destroy.

The comment # forces replacement points to the responsible argument: Terraform deletes the VM then creates another one, with a new id and a new uuid. The summary confirms it: one resource added and one deleted. The lab at the end of the page has you make this distinction before applying.

Step 4, terraform apply

terraform apply runs the changes displayed by plan. By default, it prints the plan then asks for confirmation: type yes to continue.

Terminal window
terraform apply

To automate (scripts, CI/CD):

Terminal window
terraform apply -auto-approve

Excerpt of the expected result (the plan that apply prints first is omitted):

libvirt_volume.disk: Creating...
libvirt_volume.disk: Creation complete after 1s [id=/var/lib/libvirt/images/workflow-demo.qcow2]
libvirt_domain.vm: Creating...
libvirt_domain.vm: Creation complete after 1s [name=workflow-demo]
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
vm_name = "workflow-demo"

Terraform prints one line per resource, Creating... then Creation complete. The summary Apply complete! Resources: 2 added confirms the two creations. Terraform also writes the terraform.tfstate file after each apply. The vm_name value comes from the output block of the complete example further down.

Step 5, terraform destroy

terraform destroy deletes all the resources managed by the current state. It is the opposite operation of apply.

Terminal window
terraform destroy

Or without confirmation:

Terminal window
terraform destroy -auto-approve

Without -auto-approve, Terraform first lists the resources it is going to delete and asks for confirmation. Once the operation is finished, it prints Destroy complete! Resources: N destroyed., where N is the number of deleted resources: check that it matches what you expected.

To see the effect on the libvirt side, list the virtual machines:

Terminal window
virsh -c qemu:///system list --all

The workflow-demo VM must no longer appear in the list. Terraform has also updated the state: terraform state list then no longer returns the two resources.

How do you prepare KVM for the example?

The example needs three things on the machine: libvirt installed, with your user allowed to connect to it; a storage pool (a folder managed by libvirt, where the VM disks are stored) and a virtual network (to which the VMs connect), both named default and started; an Ubuntu 24.04 image at the expected location. The commands in this section set this up on Debian 13. The guide Install KVM/libvirt on Linux (in French) covers the complete KVM installation.

How do you install libvirt and allow your user?

The three packages install the QEMU emulator, the libvirt service and the virsh client. The usermod command adds your account to the libvirt group, the one that gives access to the libvirt system connection without sudo.

Terminal window
sudo apt update
sudo apt install -y qemu-system-x86 libvirt-daemon-system libvirt-clients
sudo usermod -aG libvirt "$USER"

Then check the connection by listing the pools and networks of libvirt:

Terminal window
virsh -c qemu:///system pool-list --all
virsh -c qemu:///system net-list --all

On a freshly installed Debian 13, there is no pool, and the default network exists but is not started:

Name State Autostart
---------------------------
Name State Autostart Persistent
----------------------------------------------
default inactive no yes

The -c qemu:///system option designates the system libvirt, the one that the example uses (uri = "qemu:///system" in providers.tf). Without it, virsh run by a regular user queries qemu:///session by default, your personal libvirt: virsh uri shows it, and the list is empty. The LIBVIRT_DEFAULT_URI variable or the uri_default parameter of ~/.config/libvirt/libvirt.conf can change this choice.

Before the group is added, the same command fails with error: authentication unavailable: no polkit agent available to authenticate action 'org.libvirt.unix.manage': it is the sign of a user who does not have access yet. On Debian 13, the command succeeded as soon as usermod had run, without opening a new session, even though id did not yet show the group. This is not a general rule: if the command still fails on your machine, open a new session, then run it again.

How do you create the pool and start the network?

The default pool points to /var/lib/libvirt/images, where the provider stores the disk of the VM. The commands below define it, create the folder, start it and launch it at every boot of the machine. If pool-list already shows one named default, skip this step. The default network already exists: it only needs to be started, then launched at boot as well.

Terminal window
virsh -c qemu:///system pool-define-as default dir --target /var/lib/libvirt/images
virsh -c qemu:///system pool-build default
virsh -c qemu:///system pool-start default
virsh -c qemu:///system pool-autostart default
virsh -c qemu:///system net-start default
virsh -c qemu:///system net-autostart default

Run the two list commands again: the pool and the network must be active with autostart set to yes.

Name State Autostart
-------------------------------
default active yes
Name State Autostart Persistent
--------------------------------------------
default active yes yes

How do you download and verify the Ubuntu 24.04 image?

The example clones an Ubuntu 24.04 cloud image, a system disk ready to boot, of about 600 MB. You download it together with the list of its SHA256 sums, then sha256sum compares the image with that list. The mv comes last, because the list mentions the old name of the file.

Terminal window
mkdir -p ~/images && cd ~/images
curl -fLO https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img
curl -fsSLO https://cloud-images.ubuntu.com/noble/current/SHA256SUMS
sha256sum --check --ignore-missing SHA256SUMS
mv noble-server-cloudimg-amd64.img ubuntu-24.04-cloudimg.img

The verification must answer OK:

noble-server-cloudimg-amd64.img: OK

--ignore-missing skips the lines of the list whose file is not there. An answer of FAILED means that the download is damaged: delete the image and start again. The file ~/images/ubuntu-24.04-cloudimg.img is now the one that main.tf reads.

Complete example on KVM/libvirt

These commands work on Debian 13 (libvirt 11.3.0, KVM active), run by a regular user, with Terraform 1.17.2 and libvirt provider 0.9.9. Another distribution may change the package names, and a libvirt provider from another series changes the arguments: the schema of 0.9 differs from that of 0.8. The code is split into three files, as the HashiCorp style guide recommends: the version constraints in terraform.tf, the provider configuration in providers.tf, the resources in main.tf. The terraform, provider and resource blocks are detailed in Providers, resources and data sources. Just keep in mind here that main.tf describes a disk volume, then a VM that boots from that volume.

terraform.tf:

terraform {
required_version = ">= 1.11.0"
required_providers {
libvirt = {
source = "dmacvicar/libvirt"
version = "~> 0.9.0"
}
}
}

providers.tf:

provider "libvirt" {
uri = "qemu:///system"
}

main.tf:

resource "libvirt_volume" "disk" {
name = "workflow-demo.qcow2"
pool = "default"
target = {
format = { type = "qcow2" }
}
create = {
content = {
url = pathexpand("~/images/ubuntu-24.04-cloudimg.img")
}
}
}
resource "libvirt_domain" "vm" {
name = "workflow-demo"
type = "kvm"
memory = 512
memory_unit = "MiB"
vcpu = 1
running = true # without it, the VM is created but stays stopped
os = {
type = "hvm"
type_arch = "x86_64"
type_machine = "q35"
}
devices = {
disks = [
{
source = {
file = { file = libvirt_volume.disk.path }
}
target = {
dev = "vda"
bus = "virtio"
}
driver = { type = "qcow2" } # without it, libvirt reads the disk as raw
}
]
interfaces = [
{
model = { type = "virtio" }
source = { network = { network = "default" } }
}
]
}
}
output "vm_name" {
value = libvirt_domain.vm.name
}

Running the complete cycle: in the folder that contains the three files, type these commands. The comments give what each one must print.

Terminal window
terraform init
terraform validate # Success! The configuration is valid.
terraform plan # Plan: 2 to add, 0 to change, 0 to destroy.
terraform apply -auto-approve
virsh -c qemu:///system list --all # workflow-demo running
terraform destroy -auto-approve
virsh -c qemu:///system list --all # workflow-demo no longer appears

After the apply, the first virsh list shows the VM running:

Id Name State
-------------------------------
1 workflow-demo running

The -c qemu:///system is essential: without it, virsh queries qemu:///session by default and returns an empty list, even though the VM is running.

The two commented lines of main.tf are not decorative. Without running = true, the libvirt provider 0.9 creates the VM without starting it, and virsh -c qemu:///system list --all shows it as shut off. Without driver = { type = "qcow2" }, libvirt declares the disk as raw: the VM runs, but finds no system to boot. In the url argument, pathexpand replaces ~ with the path of your home directory.

What does Terraform remember between two applies?

After each apply, Terraform writes a terraform.tfstate file that records the correspondence between the configuration and the infrastructure objects. At the next plan, it combines three sources, and their comparison gives the proposed actions:

SourceWhat it provides
Your .tf filesthe wanted state
terraform.tfstatethe correspondence known to Terraform
The provider APIthe observed current state

The state is not the list of what exists: it is the memory of Terraform about the objects it manages. The plan also rereads the real infrastructure through the providers. Without the state, Terraform no longer knows which objects it manages: do not delete it by hand.

The state is covered in detail in Manage the Terraform state (in French).

What are the complementary commands?

The init, plan, apply, destroy cycle is enough to drive an infrastructure, but other commands are used every day without touching the infrastructure: format the code, display the outputs and the state, or test an expression in the console. Only terraform fmt changes anything, and that is your .tf files.

CommandRole
terraform fmtReformats the .tf files according to the official style
terraform outputDisplays the values of the outputs after apply
terraform showDisplays the current state in a readable way
terraform consoleOpens a REPL, a prompt where you type an expression and read its result straight away
terraform state listLists the resources in the state

Put it into practice

A configuration that has already been applied has to evolve. Before the apply, the lab asks you to say which resources will be changed in place and which will be destroyed then recreated. You read it in the actions field of the plan converted to JSON (terraform show -json), then you apply exactly the saved plan that you reviewed.

Key takeaways

  • The usual cycle chains init, validate, plan then apply.
  • plan is non-destructive: it only displays the changes. Read it before every apply: + creates, ~ changes in place, -/+ replaces, - deletes.
  • apply changes the infrastructure and updates the state.
  • destroy deletes all the managed resources.
  • The state is the link between your code and the real infrastructure.