Plain language
Infrastructure as Code means you define infrastructure in text files instead of clicking through consoles or running one-off commands. Examples of infrastructure include servers, networks, DNS records, and SaaS settings. The files go into version control, and a tool reads them and makes reality match.
There are two styles of IaC:
| Style | You describe… | Example tools |
|---|---|---|
| Imperative | The steps to reach a result ("create a VM, then attach a disk") | Bash scripts, cloud CLIs, SDK scripts |
| Declarative | The end state you want ("one VM with one disk should exist") | Terraform, CloudFormation, Kubernetes manifests |
Terraform is declarative. You write what should exist, and Terraform works out how to get there.
Under the hood
Terraform handles every run in four steps:
- Read your configuration. This is the desired state.
- Read the state file and refresh it against the real APIs. This produces the current known state.
- Compute the difference and build a dependency graph from the references between resources.
- Call the provider to create, update, or delete objects. Independent resources run in parallel, 10 at a time by default.
Because Terraform always compares desired state to actual state, running the same configuration again changes nothing. This property is called idempotency.
Annotated example: imperative vs. declarative
# Imperative: run this twice and you get two files with different names,
# or an error. The script doesn't know what already exists.
NAME="server-$RANDOM"
echo "server_name = $NAME" > inventory.txt# Declarative: run this any number of times and you get exactly one
# random name and one file. Terraform tracks what it already created.
resource "random_pet" "server" {
length = 2
}
resource "local_file" "inventory" {
filename = "${path.module}/inventory.txt"
content = "server_name = ${random_pet.server.id}\n" # reference = implicit dependency
}