Draw the garden, don't shout the jobs
Imagine making a garden by shouting jobs at helpers, one at a time: "dig a hole there", "now plant a rose". It works once. But next year nobody remembers how the garden was made, and nobody could make the same garden again next door.
So instead you draw a garden plan: a drawing of the finished garden. A rose bed here, an apple tree there, a shed in the corner. You don't write the steps, only the result you want. A gardener reads the plan and works out the steps on their own.
A plan on paper has other good points. Friends can look it over before anyone picks up a spade. You keep every old version in a folder, so you can see who moved the pond and why. And if you hand the same plan to a gardener next door, you get the same garden.
Hand the gardener the plan a second time and nothing happens: the garden already looks like the drawing, so there is nothing to do.
Infrastructure as code
Infrastructure as code (IaC) means describing infrastructure (networks, servers, buckets, databases, DNS records, permissions) in text files that a tool turns into real resources, instead of clicking them together in a console or running one-off commands. The files are:
- repeatable: the same files build the same environment for dev, staging and prod;
- reviewable: changes go through pull requests, like application code;
- versioned: Git history shows who changed what and why, and lets you go back.
Terraform is the most widely used IaC tool. It is declarative: you describe the desired end state ("one S3
bucket named shop-photos, one EC2 instance"), and Terraform works out which API calls get there. An imperative script
("create bucket, then create instance") has to handle every starting point itself, and running it twice usually fails or
makes duplicates. A declarative configuration converges instead: applying it again when nothing has changed does nothing.
Terraform is cloud-neutral: the same language and workflow manage AWS, Google Cloud, Azure, Kubernetes, GitHub, Datadog and hundreds of other platforms. On AWS, CloudFormation is the native alternative.
Check, list, then dig
The gardener always works in the same order.
First they fetch the right toolkit for this kind of garden, because a garden on a hill needs different tools from a garden by a lake. Then they walk round the garden with your drawing and write a to-do list: plant one apple tree, move the bench, pull up the old hedge. That list is called the plan. You read it. Only when you say "go ahead" do they start digging.
The drawing itself has a few handy extras. It can have blanks you fill in each time, like "how many rose bushes". When the work is done, the gardener tells you a few facts you'll need, like where the tap is. And if you like the way a herb bed is laid out, you can draw it once and reuse that little drawing in every garden.
If one day you want the whole garden gone, there is a job for that too: the gardener clears everything on the plan.
Providers, resources and the workflow
Terraform configuration is written in HCL (HashiCorp Configuration Language) in .tf files. The main block types:
| Block | Purpose |
|---|---|
provider | A plugin that talks to one platform's API, such as hashicorp/aws |
resource | Something Terraform creates and manages: aws_s3_bucket, aws_instance |
data | Something that already exists and is only read, such as the latest AMI |
variable | An input, set per environment through -var, .tfvars files or TF_VAR_ variables |
output | A value printed after apply and readable by other configurations |
module | A reusable folder of .tf files called with its own inputs |
1terraform {2required_providers {3aws = { source = "hashicorp/aws", version = "~> 6.0" }4}5}67provider "aws" {8region = var.region9}1011variable "region" {12default = "eu-west-1"13}1415resource "aws_s3_bucket" "photos" {16bucket = "shop-photos-prod"17}1819resource "aws_instance" "web" {20ami = "ami-0abc1234"21instance_type = "t3.micro"22tags = { Name = "web", Photos = aws_s3_bucket.photos.bucket }23}2425output "bucket_arn" {26value = aws_s3_bucket.photos.arn27}
The everyday commands:
terraform initdownloads the providers (and modules) and configures the backend. It writes.terraform.lock.hcl, which pins provider versions; commit it.terraform planrefreshes what it knows about the real resources, compares them with the configuration and prints the difference:+create,~update in place,-/+replace,-destroy. Nothing changes yet.terraform applymakes those changes.terraform plan -out=tfplanfollowed byterraform apply tfplanapplies exactly the reviewed plan, nothing more.terraform destroydeletes everything the configuration manages.
Some changes can't be made in place: changing an instance's AMI, for example, replaces it. Read -/+ lines in a plan
carefully, because replacing a database means a new, empty database unless you protect it with
lifecycle { prevent_destroy = true }.
The garden notebook
How does the gardener know what they planted last time? They keep a garden notebook: every plant they put in, where it is, and its label. When you change the plan, they compare the new drawing with the notebook, not just with what they can see, so they know which roses are theirs to look after and which belong to the neighbour.
At first the notebook lives in the gardener's pocket. That's fine for one person. But when two gardeners share a garden, each would have a different notebook, and both would plant the same tree. So the notebook moves to the shared garden shed, where everyone uses the same one.
One more rule: only one gardener may write in it at a time. Whoever starts work hangs an "in use" sign on the shed door. A second gardener who arrives sees the sign, turns back and tries again once it comes down, so they never plant over each other's work.
State, remote backends and locking
Terraform records what it manages in a state file (terraform.tfstate, JSON). For every resource it maps the
address in your code (aws_s3_bucket.photos) to the real object's ID and stores its last known attributes, plus
outputs and dependency information. The plan is the difference between configuration, state and the refreshed real
world. Without state, Terraform couldn't tell "my bucket" from "a bucket someone else made", or know what to delete
when a block is removed.
By default state is a local file, which breaks as soon as a team or a CI pipeline shares the configuration. A remote
backend stores it centrally. On AWS the usual choice is the s3 backend, keeping state in an
S3 bucket with versioning turned on (so a bad state write can be rolled back) and encryption:
1terraform {2backend "s3" {3bucket = "acme-terraform-state"4key = "shop/prod/terraform.tfstate"5region = "eu-west-1"6encrypt = true7use_lockfile = true8}9}
State locking stops two runs from writing the same state at once. With use_lockfile = true, the S3 backend
creates a .tflock object next to the state file and removes it when the run ends; this S3-native locking is
generally available from Terraform 1.11. Older setups lock with a DynamoDB table (dynamodb_table), which is now
deprecated; both can be set together while migrating. A second plan or apply that finds the lock fails with a
lock error instead of racing; with -lock-timeout=5m it keeps retrying for up to that long instead. If a crashed run leaves a stale lock, terraform force-unlock <ID> removes it, but only
once you're sure nothing is still running.
Split state by environment and by blast radius (one state for networking, another for each service), so one bad apply or one stuck lock can't touch everything.
What has to come first
You can't plant an apple tree in a flower bed that hasn't been dug. So when the plan says "the apple tree goes in the flower bed", the gardener knows the bed comes first. And the bed sits inside the fence, so the fence goes up before that.
The gardener never needs you to write the order down. They read who depends on whom straight from the drawing. Jobs that don't depend on each other, like the fence and the shed, are done at the same time by two pairs of hands, so the work finishes sooner.
When a garden is cleared, the same order is followed backwards: the apple tree comes out before the bed is filled in.
The dependency graph
When one resource refers to another's attribute, such as subnet_id = aws_subnet.app.id, Terraform records an
implicit dependency. From all of these it builds a dependency graph and walks it: resources with no unmet
dependencies are created in parallel (up to 10 operations at once by default, set with -parallelism), and dependents
wait. Destroy walks the graph in reverse.
- Prefer references to
depends_on. Usedepends_ononly for hidden dependencies Terraform can't see, such as an IAM policy that must exist before an app starts using it. - A cycle (A refers to B, B refers to A) is an error at plan time.
- Some values, such as a new instance's ID, are "known after apply": the plan can't show them, and anything that depends on them is decided during apply.
terraform graphprints the graph in DOT format for debugging.
Someone dug by hand
The plan says a small apple tree. One summer a helper stops pruning it and lets it grow big, without touching the plan or the notebook. Now the real garden no longer matches either. That's called drift.
Next time the gardener walks round, they notice the big tree and put it on the to-do list: "prune the apple tree back to small". You then choose. If the big tree was a mistake, let the gardener prune it. If you actually wanted it big, change the plan to say so, and the gardener leaves it alone.
The opposite also happens: an old shed stood in the garden long before the plan. To have the gardener look after it, you draw it on the plan and write it in the notebook, without knocking it down and building a new one.
Drift and import
Drift is any difference between real infrastructure and what Terraform's state and configuration say: an instance
resized in the console, a tag changed by a script, a resource deleted by hand. terraform plan refreshes
state first, so it reports drift as changes it would make to put things back. You then either apply (revert the manual
change) or update the code to match (keep it). terraform plan -refresh-only shows only what changed outside Terraform,
and terraform apply -refresh-only accepts it into state without changing any resources.
To stop drift at the source, make Terraform the only writer: read-only console access for people, and changes through pull requests. Scheduled plan runs in CI catch the drift that still happens.
Resources created outside Terraform can be adopted with an import block (Terraform 1.5 and later):
1import {2to = aws_s3_bucket.legacy3id = "old-reports-bucket"4}
The next plan shows the import, and terraform plan -generate-config-out=generated.tf can write a first draft of the
matching resource block. Once applied, the resource is in state and managed like any other; the import block can be
removed. The older terraform import command does the same thing directly to state, without a plan.
Working as a team
In a shared garden, nobody hands the gardener a plan directly. You pin the new drawing on the noticeboard, the gardener writes the to-do list underneath, and a neighbour reads both. Only after they agree does the gardener dig. Every change is checked by two people, and the noticeboard remembers who agreed to what.
Two warnings. The notebook sometimes holds secrets, like the code for the shed's padlock, written in plain words. So keep the notebook locked away and let only a few people open it.
And there are other gardeners. A few years ago the company behind this gardener changed its rules about who may copy its training. A group of gardeners started their own school, teaching the very same way of reading plans and notebooks, free for anyone. Their gardeners can pick up most plans and notebooks and carry on.
Terraform in a team: CI, secrets and alternatives
The common flow, close to GitOps, runs Terraform from CI/CD rather than laptops:
- A pull request changes
.tffiles. CI runsterraform fmt -check,terraform validateandterraform plan, and posts the plan on the pull request. - A reviewer approves the code and the plan, especially any destroy or replace.
- On merge, CI runs
terraform applywith the saved plan, using short-lived cloud credentials (for example GitHub Actions OIDC into an IAM role) instead of stored keys.
Tools such as Atlantis, HCP Terraform (formerly Terraform Cloud) and Spacelift package this flow.
Secrets in state: state holds every attribute of every resource, including generated database passwords and
private keys, in plain text. sensitive = true only hides values from CLI output; they are still written to state and
plan files. Treat state as a secret: an encrypted, versioned bucket with tight IAM access. Better still, keep secrets
out entirely: let the database or a secrets manager generate and hold the password, and pass references instead.
OpenTofu: in August 2023 HashiCorp moved Terraform from the open-source MPL 2.0 licence to the Business Source
License (BSL 1.1), starting with version 1.6. The community forked the last open version as OpenTofu, which started under the Linux
Foundation, has been a CNCF project since 2025, and shipped its first stable release in January 2024. Its tofu CLI reads the same HCL and state, and uses
the same providers, so most configurations move across unchanged; the two have since diverged in newer features.
| Tool | Language | State | Clouds |
|---|---|---|---|
| Terraform / OpenTofu | HCL | State file you store (S3, HCP Terraform...) | Any, through providers |
| CloudFormation | YAML or JSON templates | Kept by AWS in the stack | AWS only |
| AWS CDK | TypeScript, Java, Python, ... | Synthesises CloudFormation | AWS only |
| Pulumi | TypeScript, Java, Python, Go, ... | Pulumi Cloud or your own backend | Any |
CloudFormation's main appeal is that AWS keeps the state and rolls back failed updates for you; Terraform's is one workflow across every platform. CDK and Pulumi trade a fixed declarative file for real programming languages, with loops, types and tests.