web-1 and web-2 were created by hand in a dashboard on the provider's website (the VPS Setup & Configuration lesson). Three months from now, who remembers their size, their region, or which SSH key went on them? If web-1 ever has to be rebuilt completely, the answers live only in the memory of whoever clicked.
Infrastructure as Code (IaC) moves that memory into files. A server and everything around it are written down as text files, and a tool makes the real server match those files. Picture the blueprint of a house and a contractor who carries a notebook. You only change the blueprint. The contractor compares the blueprint with the house that already stands, then only does the difference: an extra room means building, a new paint colour means repainting in place, but moving the foundation means demolishing the house and building it again. In the notebook, the contractor writes down everything they have built. The most popular IaC tool for creating cloud resources (what you rent from a provider, such as servers, DNS and databases) is Terraform. In Terraform, the blueprint is the .tf files, the house is the real resources at the provider, the contractor is the terraform program, and the notebook is the state.
With Terraform, all the server settings sit in files that go into Git. The infrastructure can be rebuilt exactly, has a history, and its changes are reviewed in a PR like any code. The example here uses DigitalOcean, which calls its VPS a droplet. On AWS, GCP or Hetzner the shape is the same, only the resource names differ.
web-1 in Terraform
provider "digitalocean" {} # token from the DIGITALOCEAN_TOKEN env var
resource "digitalocean_droplet" "web_1" {
name = "web-1"
region = "sgp1"
size = "s-1vcpu-1gb"
image = "ubuntu-24-04-x64"
resize_disk = false # CPU and RAM only, can be lowered again
ssh_keys = ["3b:16:bf:e4:8b:00:8b:b8:59:8c:a9:d3:f0:19:45:fa"]
tags = ["notes-api"]
}
output "web_1_ip" {
value = digitalocean_droplet.web_1.ipv4_address
}
- The language is HCL (HashiCorp Configuration Language): a block, names, then
key = value. - A
providerhere is a plugin that calls DigitalOcean's API. Its token comes from an environment variable, never from the file. Above this block there is usually aterraform { required_providers { ... } }block that pins the provider version (the full file is in the Lab). resource "digitalocean_droplet" "web_1": the resource type, then its local name (a name used only in the Terraform files). Its full address isdigitalocean_droplet.web_1.- The content is declarative: you write the end state you want, not the steps to get there.
outputprints a value only known after the server exists, such as its IP.
init, plan, apply
The four main Terraform commands:
| Command | What happens |
|---|---|
terraform init |
downloads the provider and prepares where the state lives. Once per folder. |
terraform plan |
checks the real state of things (refresh), compares it with the files, then prints a plan. Changes nothing. |
terraform apply |
prints the same plan, waits for you to type yes, then runs it and records the result in the state. |
terraform destroy |
deletes every resource recorded in the state. |
web-1 existed before this file was written. Without an extra step, apply would create a second droplet, because the state has no record of web-1 yet. So first bring the existing droplet into the state with terraform import digitalocean_droplet.web_1 412345678 (412345678 is the droplet's id). Then make sure terraform plan says No changes. Only then start changing the file.
This is the last part of the apply output after size is changed to s-2vcpu-2gb:
Enter a value: yes
digitalocean_droplet.web_1: Modifying... [id=412345678]
digitalocean_droplet.web_1: Modifications complete after 58s [id=412345678]
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
Outputs:
web_1_ip = "203.0.113.10"
Update in place or replace
Before you look at the plan, guess. If web-1's size changes from s-1vcpu-1gb to s-2vcpu-2gb, does Terraform change the existing server, or create a new one? What if region changes from sgp1 to blr1?
The plan puts a mark in front of every resource. This is the plan when size changes:
# digitalocean_droplet.web_1 will be updated in-place
~ resource "digitalocean_droplet" "web_1" {
id = "412345678"
name = "web-1"
~ size = "s-1vcpu-1gb" -> "s-2vcpu-2gb"
tags = [
"notes-api",
]
# (21 unchanged attributes hidden)
}
Plan: 0 to add, 1 to change, 0 to destroy.
~ means update in-place (changed where it is): the same server is resized, its id and IP stay. This is an excerpt of the plan when region changes (the full one is in the Lab):
# digitalocean_droplet.web_1 must be replaced
-/+ resource "digitalocean_droplet" "web_1" {
~ id = "412345678" -> (known after apply)
~ ipv4_address = "203.0.113.10" -> (known after apply)
~ region = "sgp1" -> "blr1" # forces replacement
}
Plan: 1 to add, 0 to change, 1 to destroy.
-/+ means replace: the old server is destroyed, then a new one is created. # forces replacement points at the attribute that causes it. So size changes the existing server, while region creates a new one, because a droplet cannot change region or image in place. The consequences are big: a new IP (the DNS for notes.example.com must move too), and the disk's contents are gone, the Postgres volume on it included. Always read the Plan: line before typing yes. A + alone means create (made new), and a - alone means destroy (deleted).
State: Terraform's notebook
The state is kept in terraform.tfstate, a JSON file recording which resource in the .tf files is tied to which real thing. For example, digitalocean_droplet.web_1 is droplet 412345678 with IP 203.0.113.10. Without the state, Terraform cannot link web_1 to that server, so it would create a new one. Two rules:
- Never commit the state to Git. It can hold database passwords and tokens as plain text.
- Keep it in a remote backend with locking as soon as more than one person works on it. A remote backend is a place for the state outside the laptop, such as an S3 bucket (a container for files in S3 object storage), and locking lets only one
applyrun at a time. A state on a laptop cannot be shared and can be lost, and twoapplyruns at once can corrupt it. With a backend and a lock, the second apply fails withError acquiring the state lockwhile the first one is still running.
This is the S3 backend config for the state:
terraform {
backend "s3" {
bucket = "notes-terraform-state"
key = "prod/web.tfstate"
region = "ap-southeast-1"
encrypt = true
use_lockfile = true # lock in the bucket, Terraform 1.10 and later
}
}
Older versions of Terraform use a DynamoDB table (a database from AWS, dynamodb_table) for the lock. Other backend options: an S3-compatible bucket such as DigitalOcean Spaces, or HCP Terraform (an online service from HashiCorp, the company that makes Terraform).
Drift: changed outside Terraform
When traffic spikes, Dewi resizes web-1 to s-2vcpu-4gb in the dashboard. The file and the state still say s-2vcpu-2gb. That is drift: the real server no longer matches the record. The next terraform plan refreshes first, then reports it (an excerpt of the output):
Note: Objects have changed outside of Terraform
# digitalocean_droplet.web_1 has changed
~ resource "digitalocean_droplet" "web_1" {
~ memory = 2048 -> 4096
~ size = "s-2vcpu-2gb" -> "s-2vcpu-4gb"
}
Then the plan proposes to undo it, taking web-1 back to s-2vcpu-2gb, because Terraform treats what the .tf file says as correct. There are two choices: apply to undo the resize, or write s-2vcpu-4gb into the file so the plan says No changes. Never apply without reading the plan. Many teams run terraform plan on a schedule in CI to catch drift.
A plan is a diff
Basically, plan is a diff (a list of differences) between the current state and the desired one. This planChanges function builds that diff from two objects: currentState (the resources that exist now) and desiredState (the resources written in the files):
function planChanges(currentState, desiredState) {
const creates = [];
const updates = [];
const destroys = [];
for (const name in desiredState) {
if (!currentState[name]) {
creates.push({ action: "create", resource: name, config: desiredState[name] });
} else if (JSON.stringify(currentState[name]) !== JSON.stringify(desiredState[name])) {
const changes = {};
for (const key in desiredState[name]) {
if (currentState[name][key] !== desiredState[name][key]) changes[key] = desiredState[name][key];
}
updates.push({ action: "update", resource: name, changes });
}
}
for (const name in currentState) {
if (!desiredState[name]) destroys.push({ action: "destroy", resource: name });
}
return [...creates, ...updates, ...destroys];
}
Two example results:
| current | desired | Result |
|---|---|---|
{ server1: { type: "t3.micro" } } |
{ server1: { type: "t3.small" }, server2: { type: "t3.micro" } } |
create server2 with config, then update server1 with changes: { type: "t3.small" } |
{ db: { size: "10GB" }, cache: { size: "1GB" } } |
{ db: { size: "10GB" } } |
destroy cache; db is the same and skipped |
- In desired but not in current: create, carrying the whole
config. - In both but different: update, and
changesholds only the attributes that changed, with their new values. - In current but not in desired: destroy. Identical ones are skipped.
- The result is ordered: every create, then updates, then destroys.
Terraform and Ansible
Terraform creates and changes resources through a provider's API: servers, DNS, databases, buckets. That work is called provisioning (providing resources). Ansible goes inside a server over SSH and sets up what is in it: packages, config files, services. That work is called configuration management (setting up what is inside a server). Both are idempotent: run ten times, the end result is the same as running once, because both check the current state first and only do the difference. Alternatives to Terraform: OpenTofu (its open source fork) and Pulumi (written in languages such as TypeScript, Python or Go).
⚠️ The quickest ways to lose a server with Terraform
- Typing
yeswithout reading the plan. One-/+on a database server means its data is gone. Protect important resources withlifecycle { prevent_destroy = true }. - State in Git or only on a laptop. Secrets leak, and two people's applies overwrite each other. Use a remote backend with locking and encryption.
- Fixing things in the dashboard and forgetting. The next apply quietly undoes the change. Write changes into the files, or read the drift in the plan.
- In the exercise: the order of the result or what goes in
changes. Every create first, then updates, then destroys.changesonly holds the attributes that differ, and identical resources do not appear in the result. The result is compared as JSON text, so the order is checked too.
TL;DR: IaC (Infrastructure as Code) writes infrastructure as files that go into Git, so it can be rebuilt, has a history, and gets reviewed. Terraform reads provider blocks (plugins for a provider's API) and resource blocks (servers, DNS, databases), written in HCL (Terraform's config language) in a declarative way: you write the end state, not the steps. init downloads the provider, plan refreshes (checks the real state of things) and prints a plan without changing anything, apply runs it after you type yes, and destroy removes everything. In a plan, ~ means update in place (size: same server, same IP), -/+ means replace because of an attribute marked # forces replacement (region, image: new server, new IP, disk gone). The state (terraform.tfstate) records which resource is tied to which real thing: never commit it, keep it in a remote backend (outside the laptop) with locking. Drift appears when someone changes a server outside Terraform, and the plan reports it as "Objects have changed outside of Terraform". A plan is basically a diff (a list of differences): create, then update with the changed attributes, then destroy. Terraform for provisioning (creating resources), Ansible for setting up what runs inside a server.
⚡ A server written as a file
Write:
resource "digitalocean_droplet" "web_1" {
name = "web-1"
region = "sgp1"
size = "s-1vcpu-1gb"
image = "ubuntu-24-04-x64"
}
Meaning: This is web-1, a droplet (a VPS at DigitalOcean), written in Terraform. The content is declarative: you write the end state you want, not the steps. Writing servers as files is called Infrastructure as Code (IaC). This file goes into Git, so the server can be rebuilt exactly, has a history, and its changes are reviewed in a PR (pull request). The most popular IaC tool for this is Terraform.
⚡ init, plan, apply
Write:
terraform init
terraform plan
terraform apply
Meaning: init downloads the provider (the plugin for DigitalOcean's API), once per folder. plan checks the real state of things, compares it with the files, then prints a plan without changing anything. apply runs that plan after you type yes.
⚡ Changed in place, or replaced
Write:
~ size = "s-1vcpu-1gb" -> "s-2vcpu-2gb"
~ region = "sgp1" -> "blr1" # forces replacement
Guess first: these two lines come from a plan. If size changes, is the existing server changed, or a new one created? And when region changes?
size changes the existing server: its id and IP stay. region creates a new server because it is marked # forces replacement: a new IP, and the disk's contents are gone.
Meaning: The plan puts a mark in front of every resource: ~ means changed in place, -/+ means destroyed and created again. Inside each resource, every line that changes is marked ~, like the two lines above. Always read the Plan: line (the count of what is added, changed and destroyed) before typing yes.
⚡ State: Terraform's notebook
Meaning: The state is Terraform's notebook: the terraform.tfstate file that records which resource in the files is tied to which real thing (web_1 is droplet 412345678). Never commit the state to Git, since it can hold passwords. Keep it in a remote backend (a place for the state outside the laptop, such as an S3 bucket) with locking, so two applies never run at the same time. Changes made in the dashboard cause drift (the real server differs from the record), and the next plan proposes to undo them.