Accent colour
 
Shortcuts: press ?
 

Infrastructure as Code: A Practical Guide to Cloud Automation

Muhammad Tahir December 05, 2026

The Friday afternoon server

A small team I know once ran its whole product on a single server that only one engineer really understood. He had built it over two years, clicking through a cloud console here, running a shell command there, and never writing any of it down. Then he went on holiday, the disk filled up, and the site went down. The engineer left on call spent six hours guessing which packages were installed, which ports were open, and what the database password was. He rebuilt it from memory and old chat messages. It came back up, but nobody could say whether it matched what was there before.

That is the problem infrastructure as code exists to solve. A server built by hand is a story told from memory, and memory is a bad place to keep a production system. Infrastructure as code, usually shortened to IaC, means describing your servers, networks, databases, and permissions in text files that live in version control, and letting a tool build the real thing from those files. The file becomes the record of what exists. If the server dies, you run the file again. If someone asks why a port is open, the answer is in the file, with a commit message and a name attached. This article explains how that works, and where it gets in the way.

What infrastructure as code actually means

At its simplest, IaC is a shift in where the truth lives. In the old way, the truth lived in the running system. You opened a console, clicked "create server", and the server was the record. With IaC, the truth lives in a file. You write down what you want — a virtual machine, a database, a network, a firewall rule — and a tool reads that file and makes the real world match it.

The file is ordinary text, and that matters more than it sounds. Text files can be reviewed like code, so a second person reads a change before it goes live. They can be versioned, so you can see exactly what changed last Tuesday and roll it back. A team that keeps its infrastructure in files can answer questions a team with hand-built servers cannot: who changed this, when, why, and what did it look like before?

The tools split into a few families. Terraform, from HashiCorp, is the most widely used: it works across Amazon Web Services, Google Cloud, Azure, and dozens of other providers, and its configuration language, HCL, is designed to be read by humans. Pulumi does the same job but lets you write the configuration in Python, TypeScript, or Go. AWS CloudFormation is Amazon's own tool, limited to AWS but deeply integrated with it. Ansible and Chef configure machines that already exist, rather than creating them. The same approach can even describe a whole Kubernetes cluster, so the cluster itself is as reproducible as the servers under it.

Describing the end, not the steps

The most important idea in modern IaC is that the file is declarative. You describe the result you want, not the steps to get there. An imperative script says "create a database, then set its size to medium, then turn on backups, then open the firewall". A declarative file says "there is a database, medium size, backups on, firewall open" — and the tool works out the steps itself.

This sounds like a small difference, but it changes everything, because the tool can compare the file against reality and work out the gap. If the database already exists and matches, the tool does nothing. If backups were switched off by hand last week, the tool notices and switches them back on. If you change the size from medium to large in the file, the tool changes just that one thing. The file is a statement of intent, and the tool is responsible for closing the gap between intent and reality.

That comparison step is also what makes IaC safe to run repeatedly. A well-written configuration is idempotent: running it twice gives the same result as running it once. The first run creates the database. The second run looks, sees it is already there, and does nothing. A shell script cannot tell you what it is about to change, because it does not know what the world looked like before it ran. That preview is one of the main reasons teams trust declarative tools with production. Terraform's plan command prints a list of exactly what will be created, changed, or destroyed before anything happens. That list is the moment where a human can stop a mistake.

How a Terraform-style tool works

Here is the smallest useful example: a single virtual server on AWS. In Terraform's language, it looks like this:

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"

  tags = {
    Name = "web-server"
  }
}

That is the whole file, more or less. It says: there is a server, it uses this machine image, it is this size, and it carries a name tag. Running terraform apply reads the file, talks to the AWS API, and creates the server. Running it again does nothing, because the server already exists and matches.

Three things happen behind that short command. First, the tool reads all the files and builds a model of what you want. Second, it asks the cloud provider what actually exists right now. Third, it compares the two and builds a plan: create this, change that, destroy the other thing. Only after showing you the plan does it carry out the changes, calling the provider's API for each one. Terraform does not know anything about AWS by itself; it talks through a provider plugin that translates the generic configuration into AWS API calls. Providers exist for the big clouds, for DNS, databases, monitoring, and hundreds of smaller services, so one tool can describe infrastructure spread across several providers.

The language is small — a weekend is enough to write something real. The hard part is learning what the provider offers: security groups, subnets, instance types. IaC does not remove the need to understand infrastructure; it gives you a better place to record that understanding.

The state file: the part nobody warns you about

Every beginner's guide to Terraform mentions the state file in passing. Experienced users talk about it the way sailors talk about the weather: constantly, and with respect. The state file is the tool's memory. It records which real-world resources correspond to which blocks in your configuration, along with their IDs and settings. When you run terraform plan, the tool reads the state file, asks the provider what those resources look like now, and compares that against the configuration. Without the state file, the tool would have no way to know that the server it is looking at is the one your file describes, rather than some other server that happens to look similar.

That makes the state file the single most sensitive part of the setup. If it is deleted, the tool forgets everything it built, and the next run will try to create a second copy of all of it. If two people run the tool at the same time against the same state file, they can overwrite each other's changes. If the file contains database passwords — and by default it often does, in plain text — anyone who can read it can read your secrets. HashiCorp's own documentation on remote state is the place to read about the options before your first real deployment, not after a problem.

The standard answer is to store state remotely, in a shared location with locking. For AWS, that usually means an S3 bucket with versioning turned on, plus a DynamoDB table that provides a lock so only one person can apply changes at a time. Google Cloud and Azure have their own equivalents, and Terraform Cloud and Pulumi Cloud offer managed state as a service. The rule is simple: state belongs in a shared, locked, backed-up place, never on one person's laptop, never in version control. Keep secrets out of the configuration files too — read them from a secrets manager — and split state by boundary, one file per service or environment, so a change to staging cannot accidentally touch the production database.

Drift: when reality and the file disagree

Drift is the word for the gap between what the file says and what actually exists. It happens constantly, and it happens for innocent reasons. An engineer under pressure at 2 a.m. opens the cloud console and changes a firewall rule to let a customer in. A teammate resizes a database through the dashboard because it is faster than editing a file and waiting for a review. None of these are sabotage. Each one quietly makes the file a little less true.

Small drift is harmless. A tag changed by hand is not going to bring a site down. The danger is that drift accumulates unseen, and then one day someone runs the IaC tool and it tries to put everything back the way the file says — which now means undoing months of manual fixes. The 2 a.m. firewall rule disappears. The resized database shrinks back. That is not a bug in the tool; the tool is doing exactly what it was asked to do. The problem is that nobody noticed the file and reality had parted ways. Hand-edited settings are a common source of cloud misconfigurations, which is another reason the file should stay the only way production changes.

Three habits keep drift under control. First, make the file the only way to change production. If the console is open for reading but changes go through a pull request, drift has nowhere to start. Second, run the plan step on a schedule, even when nobody is changing anything. A nightly plan that reports "no changes" is a cheap alarm; one that suddenly lists changes is a warning that someone went around the file. Third, when drift is found, fix the file, not the cloud. If someone resized the database by hand for a good reason, put the new size in the file and commit it. Drift detection itself is still imperfect: Terraform's plan shows drift in the resources it manages, but it cannot see resources created entirely outside its state.

Modules: reuse without copy-paste

The first time a team writes infrastructure code, it writes one big file. The second time it needs a similar setup — a second environment, a second service — it copies the file and changes a few values. By the fourth copy, the files have quietly diverged: one has a fix the others lack, one has a typo, and nobody remembers which copy is the good one. This is the same trap as copying and pasting application code, and it has the same fix: put the repeated part in one place and reuse it.

In Terraform, that place is a module: a folder of configuration files that takes inputs and produces outputs. A team might write a module called web-service that takes a name and a size, and creates a server, a load balancer, and the right firewall rules. Each environment — staging, production — then calls the module with different inputs. Fix the module once, and every environment gets the fix. The same idea exists in Pulumi as reusable components and in CloudFormation as nested stacks.

Modules work best when they stay small and honest. A module that tries to cover every possible case becomes a maze of options, and teams end up fighting it instead of using it. A good rule is that a module should hide a real decision: the set of firewall rules a web service needs, the backup settings a database should have, the tags every resource in your company must carry. A module that only saves ten lines of typing is probably not worth the abstraction. One that makes sure nobody can create a database without backups is earning its keep.

Testing infrastructure code

Application developers test their code as a matter of course. Infrastructure code is often held to a lower standard, which is strange, because a bug in infrastructure code can delete a database. Testing IaC is less mature than testing application code, but the practices that exist are worth adopting, starting with the cheapest ones.

The first test is free: the plan. Every change should go through a pull request, and the plan output should be attached to that request, so a reviewer can see exactly what will change before approving it. That one habit catches more mistakes than any other — a reviewer who sees "destroy database" in a plan will ask a question, and that question is the whole point. Teams handling production data usually require a second person to approve destructive changes, and use safeguards such as Terraform's prevent_destroy setting.

The second layer is policy checks. Tools such as Open Policy Agent and HashiCorp Sentinel let you write rules about what the infrastructure is allowed to look like: no databases open to the whole internet, no storage buckets without encryption, no servers in the wrong region. The check runs automatically on every plan, and a change that breaks a rule is blocked. The third layer is real tests of the infrastructure itself. Frameworks such as Terratest let you write a test that applies a configuration, checks that the server responds, and then destroys everything. That is slower and more expensive than a plan review, so it is used for shared modules rather than for every change. One honest limitation remains: none of this tests whether the infrastructure is right for the product. A plan can tell you that a database will be created; it cannot tell you that it is too small for your traffic. Those judgements still belong to the people who understand the system.

When a script is the right tool instead

Not every infrastructure task belongs in a declarative tool. Configuring the inside of a machine — installing packages, writing configuration files, starting services in the right order — is a job where imperative tools like Ansible shine. Ansible reads a playbook, a list of steps written in YAML, connects to a server over SSH, and carries the steps out. It is excellent at "make this server look like this", and it is the tool many teams reach for when they need to install software on machines that already exist.

The honest comparison is not which tool is better, but which job each one fits.

JobBest fit
Creating servers, networks, databasesTerraform, Pulumi, CloudFormation
Installing software and configuring machinesAnsible, Chef
Describing a whole environment in one placeTerraform or Pulumi
Quick fix on one machineAnsible, or even a shell script
Enforcing rules about what may existPolicy checks on the declarative side

Most real setups use both. A common pattern is Terraform to create the machines and Ansible to configure them: the declarative tool builds the shape of the system, and the imperative tool fills in the details. The shell script has its place too: a short script for a one-off experiment is fine. The trouble starts when the experiment becomes production and the script becomes the only record of how it was built. If it cannot be run twice safely, or someone else could not rebuild the system from it, the script has outgrown its job.

When infrastructure as code is overkill

For all of this, IaC is not always the right call, and the people who sell it rarely say so. The clearest case is a single server, or a handful of resources, that change rarely. If you run one small website on a single virtual machine and you touch its setup twice a year, a Terraform configuration with remote state, locking, modules, and a review pipeline is a heavier system than the thing it manages. A short document describing the setup, plus a backup, will serve you better.

The third case is a legacy system that nobody wants to touch. Moving a ten-year-old setup into Terraform means describing every resource in code and importing it into state, one resource at a time, and the risk of breaking something that currently works is real. Some teams do it gradually, importing only the services they actively change; others leave the old system alone and put only new work in code. The test is simple: does the cost of keeping the code true stay lower than the cost of the mistakes it prevents? For a team of five running production for paying customers, the answer is almost always yes. For a hobby project with one server and no users, it is almost always no.

Questions teams ask before adopting IaC

Do we have to move everything into code at once?

No. The teams that succeed usually start with one thing — often the network, or a single service — and expand from there. Importing existing resources into Terraform state is a supported workflow: the tool can adopt a resource that already exists and start managing it.

Is Terraform the same as infrastructure as code?

No, Terraform is one tool for doing it, and the most widely used one. Pulumi, CloudFormation, and others do the same job with different trade-offs. The idea — infrastructure described in versioned text files — is bigger than any single tool, and choosing a tool matters less than the discipline of keeping the files true.

What happens if the state file is lost?

You can recover, but it is work. The resources still exist in the cloud; what is lost is the tool's record of which resources belong to which configuration. Terraform can rebuild state by importing each resource one at a time, and remote state with versioning makes the loss unlikely in the first place.

Does IaC make outages impossible?

It makes some kinds of outage less likely — the "someone changed the wrong thing by hand" kind — and it makes recovery faster, because a known-good configuration can be reapplied. But a bad change in code can also take a system down, and it can do it faster and more thoroughly than a hand-made mistake, because the tool applies the change everywhere at once. That is why plan reviews and policy checks matter: automation multiplies the effect of a mistake as surely as a good decision.

A sane way to start

The starting point is smaller than most guides suggest. Pick one thing — the staging environment, or a single service that changes often — and write the configuration for it. Store the state remotely with locking. Put the files in version control. Set up a pull request flow where the plan is posted for review before anything is applied.

Then expand slowly, in the direction of the pain. If drift keeps appearing, tighten the rules about console edits. If the same service keeps being built by hand, turn it into a module. If a mistake slips through review, add a policy check that would have caught it. The goal was never perfect files. It was to stop keeping the production system in one person's head. A file that a whole team can read, review, and rebuild from is a better place for that knowledge than memory, a chat log, or a server that only one engineer understands. Start small, keep the file true, and let it grow with the system it describes.

Was this article helpful?

Muhammad Tahir

Author

 

Get new articles by email

 

Comments