Immutable infrastructure and golden images

Intermediate · 28 min

Stop patching live servers. Bake a versioned machine image with Packer, test it, and replace servers instead of changing them, so no server can drift.

Before thisConfiguration management with AnsibleImages, layers and writing a DockerfileInfrastructure as code: declarative vs imperative

KodeKloud · 29 min · from 0:42

Immutable infrastructure and golden images

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by KodeKloudReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Servers changed in place drift apart over time, through hand fixes, failed runs and different update dates, until no two are the same.
  • Immutable infrastructure never modifies a running server. To change anything, you build a new image and replace the servers with ones made from it.
  • A golden image is a pre-built, tested machine image with the OS, patches, agents and often the app baked in. Packer builds one from a template, often using Ansible or shell to configure it.
  • Rollback becomes redeploying the previous image, and every server in a group is known to be identical because they all started from one image ID.
  • Anything that must survive a replacement, such as data, logs and secrets, has to live outside the image, in volumes, managed services or a secret store.

The server nobody dares touch

Every long-running fleet has one: the server that has been up for 900 days. During an incident three years ago someone edited a config file on it by hand. A playbook run in 2024 failed halfway on it because the disk was full. Its packages were updated on a different day from its neighbours. It works, nobody knows exactly why, and nobody wants to reboot it. The industry calls these snowflakes, each one unique.

Ansible narrows this gap by re-applying the desired state, but it only controls what the playbook mentions. Everything else on the machine is free to drift.

Seeing drift

To make drift concrete, I copied nginx’s real /etc/nginx directory, taken from the official image in images and layers, into two folders standing in for two servers, web-1 and web-2. (I left out one symlink that points outside the directory.) A short Python script hashes every file and the tree as a whole:

$ python3 treehash.py web-1 web-2
web-1: 1004fb8d2db0   web-2: 1004fb8d2db0

Identical, as you would expect from two servers built the same way. Then I made the kind of “quick fix” that happens during an incident, raising keepalive_timeout from 65 to 300 on web-2 only:

$ python3 treehash.py web-1 web-2
web-1: 1004fb8d2db0   web-2: 19821c747e61
  differs: nginx.conf

The tool found it here because I knew where to look and had a clean copy to compare with. On a real server the change could be anywhere in tens of thousands of files, and there is no clean copy unless you kept one. Mutable servers turn “are these the same?” into a question you can rarely answer.

Never change, always replace

Immutable infrastructure removes the question. Once a server is running, nothing changes on it, not packages, not config, not the app. To change anything, you build a new image, start new servers from it, move traffic to them, and delete the old ones. Every server in a group was started from the same image ID, so they are identical by construction.

This is the old “pets versus cattle” line. Pets have names and get nursed back to health. Cattle are numbered, and a sick one is replaced. It is also exactly how containers already work: you never apt-get upgrade inside a running container, you build a new image and redeploy. Golden images apply the same discipline to whole virtual machines.

Baking a golden image with Packer

A golden image is a machine image, such as an AWS AMI or an Azure or GCP image, with everything a server needs already installed: the OS with current patches, monitoring and logging agents, hardening settings, and often the application itself. Packer is the common tool for building one. It starts a temporary VM from a base image, runs provisioners to configure it, snapshots the result as a new image and deletes the VM.

A Packer template for the notes web tier, written from Packer’s HCL docs and the Amazon and Ansible plugin docs. I did not run it, because it needs Packer, an AWS account and real cost:

packer {
  required_plugins {
    amazon  = { source = "github.com/hashicorp/amazon",  version = ">= 1.8.0" }
    ansible = { source = "github.com/hashicorp/ansible", version = ">= 1.1.0" }
  }
}

source "amazon-ebs" "web" {
  region        = "eu-west-1"
  instance_type = "t4g.small"
  ssh_username  = "admin"
  ami_name      = "notes-web-{{timestamp}}"
  source_ami_filter {
    filters     = { name = "debian-13-arm64-*", virtualization-type = "hvm" }
    owners      = ["136693071363"]   # Debian's AWS account
    most_recent = true
  }
}

build {
  sources = ["source.amazon-ebs.web"]
  provisioner "ansible" {
    playbook_file = "site.yml"
  }
}

The ansible provisioner runs the same playbook as the last lesson, once, at build time instead of against live servers. The newest releases when I checked were Packer 1.16.3 and versions 1.8.4 and 1.1.6 of the Amazon and Ansible plugins.

The pipeline around it

A golden image is only useful if it is fresh, so building it becomes a pipeline:

  1. Build on a schedule, weekly for patches, and whenever the playbook or app changes.
  2. Test by starting a server from the new image and running smoke tests against it.
  3. Promote the image ID through environments, just like an application build artifact.
  4. Roll out by pointing the server group’s launch template at the new image ID in Terraform and replacing instances a few at a time. Rolling back means pointing at the previous ID.

The costs are real. Every change, even a one-line config fix, means a bake that can take several minutes plus a rollout. Old images pile up and need cleaning. And anything that must survive replacement has to live outside the server: data on attached volumes or managed databases, logs shipped off the box, and secrets fetched at boot from a secret store, never baked into the image.

About the video

The embed is a clip, from 0:42 to 28:31, of KodeKloud’s “HashiCorp Packer Tutorial: Building Custom Images for AWS, Azure, and Docker”, published April 2023. The full video is 29 minutes 19 seconds. The clip covers its chapters on what Packer is, mutable infrastructure, mutable versus immutable, custom images, the immutable workflow with Packer, and a demo. It skips the intro and closing. It was made before some plugin version changes, so check plugin versions against current releases. English was judged from the title, description, channel and its English auto-caption track. Armon Dadgar’s 2018 talk in deeper, from HashiCorp’s co-founder, is a focused explanation of the mutable versus immutable trade-off.

Where this fits

Images and servers are now built and replaced from code. The last lesson in this group closes the loop: a controller that keeps a cluster matching what Git says, continuously: GitOps with Argo CD and Flux.

Check yourself

  1. 01Two web servers built from the same playbook a year ago now behave differently. How does that happen with mutable servers?

    Each one received a different history of changes: hand fixes during incidents, playbook runs that failed halfway, packages updated on different days. The playbook describes only part of what is on them.

  2. 02With immutable infrastructure, how do you ship an OpenSSL security patch?

    Build a new image with the patched package, test it, then roll the server group over to the new image, replacing old servers with new ones rather than patching them.

  3. 03Why must you not bake database data or secrets into a golden image?

    Servers are replaced routinely, so anything inside the image is lost or reset, and every copy of the image would carry the secret. Data lives on volumes or managed services, and secrets are fetched at boot.

  4. 04How is a container image related to a golden machine image?

    They are the same idea at different levels. Both are an immutable, versioned artifact built once by a pipeline and run unchanged, and both are replaced rather than patched.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark