Infrastructure as Code & Immutable Infrastructure
A server built by hand is a mystery a year later. Which packages were installed? Who changed that config file, and why? Can we build another one exactly like it at 3 a.m. when this one dies? Infrastructure as code (IaC) answers all three: the infrastructure is described in files, kept in Git, reviewed like code and applied by a tool.
Declarative and imperative
There are two ways to describe infrastructure:
| Style | You write | Example tools |
|---|---|---|
| Imperative | the steps: create this, then change that | shell scripts, aws CLI calls, most early automation |
| Declarative | the end state: "there is a bucket named X with these tags" | Terraform / OpenTofu, Kubernetes manifests, Helm, CloudFormation, Ansible (mostly) |
Declarative tools work in a loop: read the desired state from the files, read the actual state from the
real system, compute the difference, and make only the changes needed. Running them twice in a row changes nothing
the second time (they are idempotent). In Terraform this is terraform plan followed by terraform apply:
resource "aws_s3_bucket" "logs" {
bucket = "linkly-logs-staging"
tags = {
team = "platform"
env = "staging"
}
}The same loop drives Kubernetes controllers and GitOps tools such as Argo CD, so it is worth seeing once in
miniature. The model compares a desired state with the actual one and prints a plan in Terraform's style
(+ create, ~ update, - destroy):
desired = {
"bucket/logs": {"versioning": "on", "env": "staging"},
"db/main": {"size": "small", "env": "staging"},
"dns/api": {"target": "lb-1", "env": "staging"},
}
actual = {
"bucket/logs": {"versioning": "off", "env": "staging"}, # someone changed it by hand
"db/main": {"size": "small", "env": "staging"},
"vm/old-worker": {"size": "large", "env": "staging"}, # not in the code any more
}
def plan(desired, actual):
steps = []
for name in sorted(desired.keys() | actual.keys()):
want, have = desired.get(name), actual.get(name)
if have is None:
steps.append(f" + {name} {want}")
elif want is None:
steps.append(f" - {name}")
elif want != have:
diff = {k: f"{have.get(k)} -> {v}" for k, v in want.items() if have.get(k) != v}
steps.append(f" ~ {name} {diff}")
return steps
steps = plan(desired, actual)
print("\n".join(steps))
print(f"Plan: {sum(s[2] == '+' for s in steps)} to add, {sum(s[2] == '~' for s in steps)} to change, "
f"{sum(s[2] == '-' for s in steps)} to destroy.")
actual = {name: dict(spec) for name, spec in desired.items()} # apply
print("second run:", plan(desired, actual) or "No changes.") ~ bucket/logs {'versioning': 'off -> on'}
+ dns/api {'target': 'lb-1', 'env': 'staging'}
- vm/old-worker
Plan: 1 to add, 1 to change, 1 to destroy.
second run: No changes.
Two lessons hide in that output. The ~ line is drift: a manual change the code did not know about, which the
next apply silently undoes. And the - line is why plans are reviewed before apply: deleting what is not in the
code is correct, until the thing being deleted is a production database someone forgot to import. The
Terraform & OpenTofu course covers state, imports and safe plans in depth.
Immutable infrastructure: replace, don't repair
The old way to update a server was to log in and change it: upgrade a package, edit a config, restart. After a year of that, no two servers are the same (configuration drift), and each one is a pet: named, unique, nursed back to health when sick.
Immutable infrastructure never changes a running server or container. To update, you build a new image (a container image or a VM image), start new instances from it, move traffic over and delete the old ones. Servers become cattle: identical, numbered, replaced rather than repaired.
| Mutable (patch in place) | Immutable (replace) | |
|---|---|---|
| an update | ssh in, change packages and files |
build a new image, roll it out |
| rollback | try to undo the changes | send traffic back to the previous image |
| what runs in production | whatever the server has become | exactly the image that was tested |
| debugging a bad server | investigate it for hours | replace it, then investigate the image |
Containers made this the default: a Docker image is built once, tagged with a version or digest, and the same bytes run in CI, staging and production. Kubernetes rolling updates replace pods instead of changing them.
Everything as code
The same idea now covers almost everything a team runs:
| What | As code with |
|---|---|
| cloud networks, databases, clusters | Terraform / OpenTofu, CloudFormation, Pulumi |
| what runs on a cluster | Kubernetes YAML, Helm charts, Kustomize overlays |
| server configuration | Ansible, cloud-init |
| pipelines | .github/workflows/*.yml, .gitlab-ci.yml |
| dashboards and alerts | Grafana dashboards as JSON, Prometheus rule files |
| policies | OPA/Rego, Kyverno policies |
Once it is all in Git, a pull request becomes the change process for infrastructure too: review, automated checks,
an audit trail, and git revert as a rollback.
Tip: The test of good IaC is simple: could you delete the staging environment and rebuild it from the repository alone, with no hand-made steps? If not, the missing steps are your next automation task.
Test yourself
What does a declarative IaC tool do when you run it twice with no change to the code?
- Creates every resource a second time
- Nothing: desired and actual state already match
- Deletes everything and recreates it
- Fails with an error
Someone changed a bucket setting in the cloud console. What will the next plan show?
- Nothing, the tool ignores manual changes
- An update that puts the setting back to what the code says (drift)
- A new bucket
- The bucket being destroyed
With immutable infrastructure, how do you update a running service?
- SSH in and upgrade the packages
- Build a new image, start new instances from it, shift traffic and remove the old ones
- Edit files inside the running container
- Restart the old server