Skip to content

Packer image builds — repeatable golden images for any provider

Packer templates, builders, and provisioners explained for the operator who needs golden images that survive across clouds, hypervisors, and time.

Packer is HashiCorp’s image builder. You give it a base image (a cloud-init enabled OS image, an ISO, an AMI), a list of provisioners (shell scripts, Ansible playbooks, Chef cookbooks), and one or more target providers (AWS AMI, libvirt qcow2, Proxmox template, VMware OVF, Vagrant box). It boots the base, runs the provisioners, snapshots the result, and uploads it as an immutable image. This article is the field guide to using Packer as the source of golden images that all your other automation (Terraform, Vagrant, ASG launch templates) consumes.

How to verify

Packer is a single binary; install it from HashiCorp’s apt repo or directly from GitHub releases. Each builder needs its own credentials or local provider setup.

packer version
packer plugins installed
# For libvirt builds
which qemu-img && qemu-img --version
# For AWS AMI builds
aws sts get-caller-identity
# Template syntax check
packer fmt -check golden.pkr.hcl
packer validate golden.pkr.hcl

packer validate parses the template and checks credentials without launching a build — always run it in CI before committing.

What’s happening

A Packer build has four phases. The builder stands up the base — boots an EC2 instance from a starting AMI, launches a qemu VM from an ISO, attaches to an already-running container. The provisioners run sequentially against that running instance — shell, Ansible, Chef, file uploads, the lot. The post-processors transform the resulting artifact — compress it, upload it elsewhere, register it as a Vagrant box. The build tears down the temporary instance and you’re left with an immutable image referenced by an ID.

HCL2 is the current template language; the older JSON syntax still works but the documentation has moved. A template has zero or more source blocks (the builders), a build block that wires sources to provisioners, and optional variable declarations. Multiple sources in one build produce parallel artifacts — the same provisioning logic baked into AWS AMI and a libvirt qcow2 in a single run.

The procedure

  1. Start with a single-source template — a libvirt qcow2 from an Ubuntu cloud image:

    variable "version" {
      type    = string
      default = "20260602.01"
    }
    
    source "qemu" "ubuntu" {
      iso_url            = "https://cloud-images.ubuntu.com/jammy/current/jammy-server-cloudimg-amd64.img"
      iso_checksum       = "file:https://cloud-images.ubuntu.com/jammy/current/SHA256SUMS"
      disk_image         = true
      disk_size          = "10G"
      format             = "qcow2"
      accelerator        = "kvm"
      ssh_username       = "ubuntu"
      ssh_private_key_file = "./build-key"
      ssh_timeout        = "10m"
      headless           = true
      shutdown_command   = "sudo shutdown -P now"
      output_directory   = "build/ubuntu-${var.version}"
      vm_name            = "ubuntu-jammy-${var.version}.qcow2"
    }
    
    build {
      sources = ["source.qemu.ubuntu"]
    
      provisioner "shell" {
        inline = [
          "sudo apt-get update",
          "sudo apt-get install -y nginx ufw",
          "sudo systemctl enable nginx",
        ]
      }
    }
  2. Build and inspect. packer build runs the whole pipeline. -on-error=ask is the operator-friendly flag — when something fails, you get a prompt to SSH into the dying instance before it gets destroyed:

    packer init golden.pkr.hcl
    packer build -on-error=ask golden.pkr.hcl
    ls -la build/ubuntu-20260602.01/
  3. Switch to Ansible — the moment shell gets painful. Anything more than a dozen lines of shell belongs in an Ansible role. Provision via the ansible provisioner; Packer spawns an SSH tunnel to the building instance and runs ansible-playbook from the host:

    provisioner "ansible" {
      playbook_file = "./ansible/site.yml"
      user          = "ubuntu"
      extra_arguments = ["--extra-vars", "build_version=${var.version}"]
    }
  4. Multi-source — same logic, multiple targets. Define a second source for AWS AMI and reference both in the build. The provisioners run independently against each — be sure your Ansible roles are idempotent and don’t assume one cloud’s metadata service is reachable on the other:

    source "amazon-ebs" "ubuntu" {
      region          = "ca-central-1"
      source_ami_filter { /* ... */ }
      instance_type   = "t3.medium"
      ami_name        = "company-base-${var.version}"
      ssh_username    = "ubuntu"
    }
    
    build {
      sources = ["source.qemu.ubuntu", "source.amazon-ebs.ubuntu"]
      # ... provisioners apply to both
    }
  5. Strip secrets at the end. A build that copied an SSH key in for provisioning must not leave that key in the image. Add a final shell provisioner to scrub:

    provisioner "shell" {
      inline = [
        "sudo rm -f /home/ubuntu/.ssh/authorized_keys",
        "sudo cloud-init clean --logs --seed",
        "sudo apt-get clean",
        "sudo truncate -s 0 /var/log/wtmp /var/log/lastlog",
        "sudo rm -f /etc/machine-id && sudo systemd-machine-id-setup",
        "sync && sudo fstrim -v /",
      ]
    }

    The cloud-init clean and the machine-id reset are essential for cloud images — without them every instance booted from this image has the same machine-id, which breaks log correlation and some daemons.

  6. Versioning and promotion. A built image’s identity is its name + a version stamp. Treat the build pipeline like an app pipeline: build in dev, smoke-test, promote to staging, then to prod. Never overwrite a published image — bump the version and let consumers move at their pace.

  7. Wire to consumers. Terraform references the AMI ID; Vagrant references the box version; libvirt references the qcow2 path. The Packer build output (packer-manifest.json from the manifest post-processor) is the source of truth — pipe it into the consumers via a small registration script.

Operational notes

  • packer build running as root sometimes fixes inscrutable provider errors but masks the real problem; build as the operator user with appropriate group memberships (libvirt, docker) instead.
  • A Packer build that hangs at “Waiting for SSH” is usually a network problem — the builder created the instance but cloud-init hasn’t finished configuring SSH, or your security group/firewall blocks port 22.
  • Cloud builders charge for the temporary instance; a failed build that leaves resources behind costs money. Tag them and have a janitor script that cleans builder instances older than a few hours.
  • Building from cloud-init-enabled images and provisioning via Ansible means you have two configuration mechanisms running on the same instance; pick one for the build (Ansible) and one for runtime (cloud-init) to avoid conflicts.
  • Image-build pipelines are CI/CD pipelines — they need credentials, secrets management, and approval gates the same as code deploys. Don’t run them on a developer laptop with long-lived cloud credentials.

Stack Harbor runs Packer pipelines as the source of golden images for clients who care about consistency across hypervisors and clouds — one Ansible codebase, one Packer template, multiple targets, versioned outputs, signed manifests. Clients whose VM templates are “the one Bob built in 2022 that nobody dares replace” get those rebuilt as part of Managed Operations.