You rerun a script that creates a VM. It fails because the resource already exists, or worse, it creates a duplicate. And to rebuild a staging environment identical to production, you have to dig up the exact order of the commands run three months ago.
Terraform works differently: instead of describing the steps to configure a server (the imperative approach), you describe the final state you want (the declarative approach).
Terraform reads the current state from the state file (where it records what it created) and from the providers' APIs (the plugins that talk to each platform). It compares that state with your configuration, written in HCL (the Terraform language), then proposes the actions needed to reach the desired state. Running Terraform again changes nothing as long as the configuration, the state and the real infrastructure are aligned: this is idempotence, which the shell script below has to achieve by hand.
This guide introduces the idea with Terraform and a libvirt example. The declarative or imperative (in French) guide in the fundamentals covers the same question for all Infrastructure as Code tools.
What you will learn
- The core difference: imperative (steps) vs declarative (final state)
- Idempotence: why running Terraform twice does not create anything twice
- How Terraform computes changes: the diff mechanism against the state
- The limits of the declarative approach: what Terraform does not handle and when to use Ansible
Imperative: describing the steps
In an imperative approach, you write the actions to perform, in order. Here is
a shell script that creates a libvirt VM: it starts by checking whether the VM
exists, then prepares the disk (growing it to 20 GB, which the HCL code further
down leaves out to stay short) and runs virt-install.
#!/bin/bash# Imperative script to create a VM
# Check whether the VM already existsif virsh -c qemu:///system list --all | grep -q "lab-vm"; then echo "The VM already exists" exit 0fi
# Copy the base image, then grow the disk to 20 GBcp ~/images/ubuntu-24.04-cloudimg.img \ /var/lib/libvirt/images/lab-vm.qcow2qemu-img resize /var/lib/libvirt/images/lab-vm.qcow2 20G
# Create the VMvirt-install \ --connect qemu:///system \ --name lab-vm \ --memory 1024 \ --vcpus 1 \ --disk /var/lib/libvirt/images/lab-vm.qcow2 \ --network default \ --osinfo ubuntu24.04 \ --import --noautoconsoleThis script says how to create the VM, and each run depends on the state left by the previous one. Three limits follow:
- The existence check only looks at the name: a VM that is already there with too little RAM is reported as "already exists" without being fixed. Changing the RAM requires extra logic.
- If the script stops between two steps, an orphan disk stays in place, and you have to remember to clean it up by hand.
- Deleting the VM requires another script.
Declarative: describing the final state
With Terraform, you only describe the result you want, here a VM with 1 GB of RAM created from an Ubuntu 24.04 image. Terraform handles the execution details.
resource "libvirt_volume" "disk" { name = "lab-vm.qcow2" pool = "default" target = { format = { type = "qcow2" } } create = { content = { url = pathexpand("~/images/ubuntu-24.04-cloudimg.img") } }}
resource "libvirt_domain" "vm" { name = "lab-vm" type = "kvm" memory = 1024 memory_unit = "MiB" vcpu = 1 running = true # ... system, disk and network: see the first infrastructure}The code contains no action verb: you do not write "create", you write "this is what must exist". Terraform computes the actions needed to go from the current state to that state by itself (the first infrastructure (in French) gives the complete example).
The key consequence: idempotence
Declarative code is idempotent: applying it a second time changes nothing if the infrastructure already matches the description.
| Situation | Imperative script | Terraform |
|---|---|---|
| Resource missing | Creates it | Creates it |
| Resource already up to date | Does nothing, only if you wrote the check | Does nothing |
| Resource partially created | Unpredictable behavior | Detects and fixes |
| Resource to modify | Logic to write by hand | Modifies automatically |
How Terraform computes changes
Terraform compares two states: the desired state, described in your .tf
files, and the actual state, read from the state file and from the
provider's API. The difference between the two (the diff) is what
terraform plan displays, and terraform apply runs the matching actions:
create, modify or destroy.
The diagram puts the two approaches side by side. The imperative script
chains steps written by hand: existence check, disk, then starting the VM with
its network through virt-install. Terraform starts from the desired
state, reads the state file to learn the current state, computes the
diff, then apply brings the infrastructure into line. The plan also
queries the provider's API, which the diagram does not show.
If the VM already has the right RAM and the right number of vCPUs,
terraform plan displays:
No changes. Your infrastructure matches the configuration.If you change the RAM from 1024 to 2048 MiB in the code, the plan announces
an in-place modification (tested on Debian 13 with Terraform 1.17.2 and the
libvirt provider 0.9.9, on a VM named lab-vm):
# libvirt_domain.vm will be updated in-place ~ resource "libvirt_domain" "vm" { id = 2 ~ memory = 1024 -> 2048 name = "lab-vm" # (7 unchanged attributes hidden) }
Plan: 0 to add, 1 to change, 0 to destroy.Read the plan from top to bottom. The ~ in front of memory indicates an
in-place modification, and 1024 -> 2048 gives the old and the new value; +
signals a creation and - a deletion. The unchanged attributes are hidden, and
the last line summarizes the plan: nothing to create, one resource to modify,
nothing to destroy. You wrote no step to go from 1024 to 2048, Terraform
deduced it from the difference between the code and reality.
What Terraform does not handle: the inside of servers
Terraform describes the infrastructure, not what runs inside it: installing packages or tuning a service on a VM is a job for other tools, such as Ansible. The page What is Terraform? details this scope.
The limits of the declarative approach
The declarative approach has limits:
- Some changes require a replacement: when an argument cannot be modified in place, Terraform destroys the object then recreates it, and the plan says so. Terraform handles it, but it is an impact to anticipate before you approve. The example below shows a real case.
- Complex sequential operations are more natural in imperative style. Terraform handles automatic dependencies, but not application workflows.
- The state can diverge from reality if resources are modified outside Terraform (console, direct CLI). This gap between the declared state and the actual state is called drift. Its causes and its correction are detailed in idempotence, convergence and drift (in French).
Renaming the VM lab-vm to autre in the code gives this plan (excerpt,
tested with Terraform 1.17.2 and the libvirt provider 0.9.9):
~ name = "lab-vm" -> "autre" # forces replacement-/+ resource "libvirt_volume" "disk" { ~ name = "lab-vm.qcow2" -> "autre.qcow2" # forces replacement
Plan: 2 to add, 0 to change, 2 to destroy.The # forces replacement comment points to the argument that forces the
resource to be replaced, here name, on the domain and on the volume. -/+
means "destroy then recreate". The last line therefore counts two creations and
two destructions: the VM's disk is recreated, and its content is lost. You read
this summary before typing yes.
Put it into practice
The lab gives you a provisioning script that diverges as soon as you replay it: a different identifier on each call, a report that piles up instead of being replaced. You get the same result with Terraform, then you check through the plan that a second run changes nothing, before fixing an external drift without touching your code.
Key points
- Imperative: you describe the steps (create, copy, start).
- Declarative: you describe the desired final state.
- Terraform is declarative: it computes the actions to perform by itself.
- Idempotence is a direct consequence: replaying the code breaks nothing.
- Terraform manages the infrastructure. Configuring the inside of servers is better done with dedicated tools such as cloud-init, Packer or Ansible.