TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท infrastructure ยท devops ยท terraform ยท opentofu

Infrastructure as code (Terraform)

Describing servers, networks and storage in versioned files that a tool turns into real infrastructure. Terraform reads declarative HCL, compares it with its state file, shows a plan of what it will create, change or destroy, and applies it in dependency order.

15 min6 animations

๐Ÿ“š Builds on๐Ÿญ CI/CD

๐Ÿ–จ๏ธ Cheat sheet

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.

Imperative script vs declarative configuration4 steps
๐Ÿก The garden๐Ÿ“ฃShouted jobs๐Ÿง‘You๐Ÿ—บ๏ธ Garden plan๐Ÿง‘โ€๐ŸŒพGardener๐Ÿ›–Shed๐ŸŒณApple tree
Press play and watch it happen!

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:

BlockPurpose
providerA plugin that talks to one platform's API, such as hashicorp/aws
resourceSomething Terraform creates and manages: aws_s3_bucket, aws_instance
dataSomething that already exists and is only read, such as the latest AMI
variableAn input, set per environment through -var, .tfvars files or TF_VAR_ variables
outputA value printed after apply and readable by other configurations
moduleA reusable folder of .tf files called with its own inputs
1terraform {2  required_providers {3    aws = { source = "hashicorp/aws", version = "~> 6.0" }4  }5}6 7provider "aws" {8  region = var.region9}10 11variable "region" {12  default = "eu-west-1"13}14 15resource "aws_s3_bucket" "photos" {16  bucket = "shop-photos-prod"17}18 19resource "aws_instance" "web" {20  ami           = "ami-0abc1234"21  instance_type = "t3.micro"22  tags          = { Name = "web", Photos = aws_s3_bucket.photos.bucket }23}24 25output "bucket_arn" {26  value = aws_s3_bucket.photos.arn27}

The everyday commands:

  1. terraform init downloads the providers (and modules) and configures the backend. It writes .terraform.lock.hcl, which pins provider versions; commit it.
  2. terraform plan refreshes 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.
  3. terraform apply makes those changes. terraform plan -out=tfplan followed by terraform apply tfplan applies exactly the reviewed plan, nothing more.
  4. terraform destroy deletes 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 }.

init, plan, apply, destroy6 steps
๐Ÿง‘You๐Ÿง‘โ€๐ŸŒพGardener๐ŸงฐTool shop
Press play and watch it happen!

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 {2  backend "s3" {3    bucket       = "acme-terraform-state"4    key          = "shop/prod/terraform.tfstate"5    region       = "eu-west-1"6    encrypt      = true7    use_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.

Remote state and locking5 steps
๐Ÿ›– Garden shed๐Ÿ‘ฉโ€๐ŸŒพGardener Ana๐Ÿ‘จโ€๐ŸŒพGardener Ben๐Ÿ“’ Garden notebook๐ŸŒณApple tree
Press play and watch it happen!

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. Use depends_on only 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 graph prints the graph in DOT format for debugging.
The dependency graph5 steps
๐Ÿง‘โ€๐ŸŒพGardener๐ŸชตFence๐ŸŒฑFlower bed๐ŸŒฟHedge๐ŸŒณApple tree๐Ÿ›–Shed
Press play and watch it happen!

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 {2  to = aws_s3_bucket.legacy3  id = "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.

Drift and import4 steps
๐Ÿง‘You๐Ÿง‘โ€๐Ÿ”งHelper๐Ÿง‘โ€๐ŸŒพGardener๐Ÿ“’ Garden notebook๐ŸŒณApple tree๐Ÿ›–Old shed
Press play and watch it happen!

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:

  1. A pull request changes .tf files. CI runs terraform fmt -check, terraform validate and terraform plan, and posts the plan on the pull request.
  2. A reviewer approves the code and the plan, especially any destroy or replace.
  3. On merge, CI runs terraform apply with 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.

ToolLanguageStateClouds
Terraform / OpenTofuHCLState file you store (S3, HCP Terraform...)Any, through providers
CloudFormationYAML or JSON templatesKept by AWS in the stackAWS only
AWS CDKTypeScript, Java, Python, ...Synthesises CloudFormationAWS only
PulumiTypeScript, Java, Python, Go, ...Pulumi Cloud or your own backendAny

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.

Plan in CI, apply after review5 steps
๐Ÿง‘You๐Ÿง‘โ€๐ŸฆฐNeighbour๐Ÿ“Œ Noticeboard๐Ÿง‘โ€๐ŸŒพGardener๐Ÿ“’ Garden notebook๐ŸกThe garden
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Infrastructure as code (Terraform), told the same way as the story.
  1. You hand the gardener the same garden plan twice in a row, and nothing in the garden has changed. What happens the second time?
  2. Gardener Ben wants to start work, but Gardener Ana's in-use sign is hanging on the shed door. What should happen?
  3. The plan says a small apple tree, but a helper let it grow big by hand. What does the gardener's next walk round show?
  4. Your plan sets the shed padlock code but marks it as hidden. Where can the code still be read?
  5. The plan says the apple tree goes in the flower bed, and the shed needs nothing. In what order does the gardener work?
Answer every question to check.Passing marks Infrastructure as code (Terraform) as done.
Got the hang of Infrastructure as code (Terraform)? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿš€ Shipping to productionStep 3 of 10

โ† Previous on the path๐Ÿญ CI/CDNext on the path โ†’๐Ÿ“ฆ Docker and containers

๐Ÿ‘‰ Read next

  • ๐Ÿ“AWS CloudFormation and CDKBuilding a house from a written plan, with a foreman who lists every change before laying a brick.