Infrastructure as Code
Why Infrastructure as Code
Infrastructure built by clicking in a console or typing commands on a server drifts: nobody remembers exactly how it was made, no two environments are alike, and rebuilding after a disaster becomes archaeology. IaC applies the discipline of software development to infrastructure.
What It Gives You
- Reproducibility: the same code produces the same infrastructure, in any account or region.
- Review and history: every change goes through a pull request, and
git logshows who changed what and why. - Speed and recovery: new environments in minutes; a lost environment rebuilt from code.
- Consistency: staging and production differ only in declared parameters, not in forgotten manual steps.
Declarative vs Imperative
An imperative script lists steps: create a network, then create a server in it. Running it twice may create two servers. A declarative definition describes the desired end state: there is one network and one server in it. The tool compares the desired state with reality and computes the steps, which makes declarative code idempotent by design. Most IaC tools are declarative; the shell scripts in Shell Automation are imperative and must be made idempotent by hand.
Tools and Their Roles
IaC tools fall into two broad families that are often used together.
Provisioning vs Configuration Management
| Family | Manages | Examples |
|---|---|---|
| Provisioning | Cloud and platform resources: networks, VMs, load balancers, databases, DNS, IAM. | Terraform, OpenTofu, Pulumi, AWS CloudFormation, Azure Bicep |
| Configuration management | What runs inside a server: packages, files, users, services. | Ansible, Chef, Puppet, Salt |
| Image building | Pre-built machine or container images. | Packer, Dockerfiles |
| Cluster state | Workloads on a container platform. | Kubernetes manifests, Helm, Kustomize, GitOps controllers |
OpenTofu is an open-source fork of Terraform, created after Terraform's license changed in 2023; the two share the same HCL language and workflow, and the examples below work with either.
The Provisioning Workflow
Terraform and OpenTofu read .tf files written in HCL. Each resource block declares one piece of infrastructure; providers translate the declarations into API calls for a platform such as AWS, Azure, Google Cloud or Kubernetes.
Declare Resources
# main.tf: a private network and one web server on AWS.
terraform {
required_version = ">= 1.6"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = var.region
}
variable "region" {
type = string
default = "eu-central-1"
}
variable "environment" {
type = string # "staging" or "production", supplied per environment
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
tags = {
Name = "main-${var.environment}"
Environment = var.environment
}
}
resource "aws_subnet" "app" {
vpc_id = aws_vpc.main.id # a reference: Terraform creates the VPC first
cidr_block = "10.0.20.0/24"
}
output "subnet_id" {
value = aws_subnet.app.id
}
References between resources, such as aws_vpc.main.id, form a dependency graph, so the tool knows the order in which to create, change or destroy things. Pin provider versions as shown; an unpinned provider upgrade can change behavior between two runs of the same code.
Plan, Review, Apply
tofu init # or: terraform init (downloads providers)
tofu fmt -check && tofu validate # style and syntax, suitable for CI
tofu plan -var environment=staging -out=staging.tfplan
tofu apply staging.tfplan # applies exactly the reviewed plan
The plan is the most important safety feature of the workflow: it lists every resource that will be created (+), changed in place (~) or destroyed (-), including replacements forced by changes to immutable attributes. In a team, the pipeline runs plan on every pull request and posts the result for review, and apply runs only after merge, from the saved plan. A plan that unexpectedly destroys a database is the cheapest possible place to catch that mistake.
State and Drift
Terraform and OpenTofu record which real resources correspond to which code blocks in a state file. State is how the tool knows that aws_vpc.main is a particular network and not a new one.
Store State Remotely and Lock It
Never keep state only on a laptop or commit it to Git: it is the only map from code to reality, and it may contain secrets such as generated passwords. Use a remote backend — object storage with versioning and encryption, or a managed service — that supports locking, so two people cannot apply at the same time. Restrict who can read the state as strictly as the infrastructure itself. Split state per environment and per component (network, data, applications) so a mistake in one plan cannot touch everything.
Detect and Correct Drift
Drift is any difference between the code and reality, usually caused by a manual change made “just this once” during an incident. Run plan on a schedule and alert when it is not empty. Then either bring the manual change into the code, or let the next apply revert it. Make console access read-only for most people, so the code stays the single source of truth.
Configuring Servers
When servers are long-lived, a configuration management tool keeps their contents in the desired state. Ansible is popular because it is agentless: it connects over SSH and runs modules that are each idempotent.
An Ansible Playbook
# web.yml: install and configure nginx on every host in the "web" group.
- name: Configure web servers
hosts: web
become: true
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
update_cache: true
- name: Deploy site configuration
ansible.builtin.template:
src: templates/site.conf.j2
dest: /etc/nginx/sites-available/default
mode: "0644"
notify: Reload nginx # runs only if the file actually changed
- name: Ensure nginx is running and enabled at boot
ansible.builtin.service:
name: nginx
state: started
enabled: true
handlers:
- name: Reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
Run it with ansible-playbook -i inventory.ini web.yml --check --diff first: check mode reports what would change without changing it. A second real run should report zero changes; if it does not, some task is not idempotent.
Immutable Infrastructure and Parity
Configuration management repairs servers in place. Immutable infrastructure takes the opposite approach: never modify a running server; replace it.
Replace, Don't Repair
With immutable infrastructure, each change produces a new machine image or container image, built and tested in the pipeline, and new instances replace old ones. Nobody logs in to patch a server, so servers cannot drift, and rolling back means starting instances from the previous image. Containers made this the default model for applications (see Containers & Virtualization). State — databases, uploaded files, queues — must live outside the replaceable instances, on managed services or dedicated volumes.
Environment Parity
Bugs that appear only in production are usually differences between environments: another version, another setting, a missing resource. Build every environment from the same code and modules, with the differences reduced to a small set of declared variables — instance sizes, replica counts, domain names. Promote the same artifact through the environments, as described in Version Control & CI/CD, and keep staging close enough to production that a successful deployment there predicts one in production.
Reuse with Modules
A module packages a set of resources behind a small interface of input variables and outputs — for example, “a service with a load balancer, an autoscaling group and alarms”. Modules let a platform team encode good defaults (encryption on, logging on, no public access) once and let product teams reuse them. Version modules like libraries and upgrade environments deliberately, staging first.
Practice Lab
Use OpenTofu or Terraform with a free local provider such as docker or local, or a cloud free tier with a strict budget alert.
Provision Declaratively
- Write a configuration that creates two resources with a dependency between them, and parameterize one value with a variable.
- Run
plan, read every line of the output, thenapply. Runplanagain and confirm it reports no changes. - Change one attribute that forces a replacement and find the
-/+marker in the plan before applying.
Create Two Environments and Detect Drift
- Deploy the same code twice as
stagingandproduction, each with its own state. - Change a resource by hand outside the tool, then run
planand explain the drift it reports. - Decide whether to adopt or revert the change, do it through code, and write down the rule your team would follow next time.