Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Packer concepts and architecture

By updated

Improve this page

Logo Packer

Packer builds machine images from a configuration file: a system that is already installed and configured, ready to be copied as many times as you like, instead of being installed by hand on each server. This lesson is for anyone who has never used Packer. It explains what a machine image is, the three components of a template (builder, provisioner, post-processor), the order of a packer build read on a real output, and when to prefer Packer over another tool. No installation is needed to read it.

What you will learn

  • Explain what a machine image is and what Packer automates about it.
  • Tell the builder, the provisioners and the post-processors apart.
  • Recognize the three blocks packer, source and build of a template.
  • Read the steps of a packer build in its output.
  • Choose between Packer, a configuration manager and a Dockerfile.

Prerequisites

No technical prerequisite: this lesson presents the concepts. To replay the commands of the following lessons, you need Packer installed (Install Packer) and Docker up and running.

What is Packer?

Packer is a tool created by HashiCorp that automates the creation of machine images. A machine image is an operating system that is already installed and configured, saved in a reusable form. Depending on the platform, it is an AMI on Amazon Web Services, a Docker image, a QCOW2 file for a KVM virtual machine or a Proxmox template. You then start as many identical machines as you want from this image.

Packer produces the image from a configuration file written in HCL, the configuration language of HashiCorp, with no manual installation and no click in an interface. Its source code is available under the BSL (Business Source License) since version 1.10.0, as the LICENSE.txt shipped with version 1.16.2 states.

What Packer brings is reproducibility. The content of the image is described in a versioned file, not in the memory of the person who built it. The table compares the two ways of working.

AspectWithout PackerWith Packer
Image creationManual installation, clicks in an interfaceOne command: packer build
Reproducibility"It worked last time"The same description at every build
DocumentationPersonal notes, outdated wikiThe HCL template describes the image
Several platformsRedo the work for each targetOne template, several sources
HistoryHard to traceTemplate versioned with Git

Why build an image rather than configure each server?

Building the image once, before deployment, avoids configuring each server when it starts. Two other approaches exist: configuring each server by hand, which is slow and impossible to reproduce, or running a configuration tool at every startup, which depends on the network and lengthens the startup.

With Packer, you create a golden image once: a reference image that contains the system, the dependencies and the security configuration you want, validated before it is used. Each machine then starts in a known state.

The gains are qualitative, not numeric:

  • machines start already configured, with no configuration step;
  • they are identical, which avoids configuration drift (servers that slowly diverge from one another);
  • security patches go into the image at build time;
  • the template shows exactly what the image contains;
  • the same description can produce images for several platforms.

What are the components of a Packer build?

A Packer build assembles three types of components, always run in the same order. The diagram shows them: the builder creates the machine, the provisioners configure it, the post-processors process the resulting image.

An HCL template (a .pkr.hcl file) contains three components run in order: the builder creates the machine, the provisioners configure the image, the post-processors finalize the artifact.HCL template (.pkr.hcl)Buildercreates the machineProvisionersconfigure the imagePost-processorsfinalize the artifact
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

An artifact is the result of the build: the image itself, or the file that points to it.

The builder creates the starting machine

The builder creates a temporary machine, then produces an image from it. Each builder matches one platform. The table gives a few builder names.

BuilderPlatformTypical use
amazon-ebsAWSAMI for EC2
azure-armAzureManaged images
googlecomputeGCPCompute Engine images
qemuKVM, libvirtLocal Linux images
proxmox-isoProxmoxVM templates
dockerDockerContainer images
virtualbox-isoVirtualBoxDeveloper workstation images

A builder is not built into Packer: it comes from a plugin, a separate program that packer init downloads to add components to Packer. This is the case of the docker builder, used throughout this course: if the plugin is declared in required_plugins but not installed, packer validate fails with Missing plugins; if it is not declared, the source type stays unknown.

A single template can cite several sources to produce several images, for example an AWS AMI and a Docker image, from the same configuration.

Provisioners configure the image

Provisioners run once the temporary machine has started. They install packages, copy files or run scripts. Packer runs them in the order they are written in the template.

Eight provisioners are built into Packer: shell, file, powershell, shell-local, breakpoint, windows-shell, windows-restart and hcp-sbom. The others come from a plugin. The table shows the first three and a few provisioners that need a plugin.

ProvisionerRoleBuilt into Packer
shellRuns shell commands or scriptsYes
fileCopies files into the imageYes
powershellRuns PowerShell scripts (Windows)Yes
ansibleRuns an Ansible playbookNo, plugin required
chef-solo, chef-clientRun ChefNo, plugin required
puppet-masterless, puppet-serverRun PuppetNo, plugin required

Without the plugin, and without a required_plugins block that declares it, Packer answers Unknown provisioner type "ansible": the type stays unknown until the plugin is installed. The bare names chef and puppet designate no type and are refused the same way. The provisioners are detailed in the lesson Packer provisioners.

Post-processors process the resulting image

Post-processors run on the artifact, once the image is created: compress, compute a checksum, record metadata, publish. Some are built in, others come from a plugin.

Post-processorActionBuilt into Packer
manifestWrites a JSON file describing the buildYes
compressCompresses the artifact into an archiveYes
checksumComputes a checksumYes
docker-tag, docker-pushTag and publish a Docker imageNo, docker plugin
vagrantConverts to a Vagrant boxNo, plugin required

Without its plugin, vagrant gives Unknown post-processor type "vagrant" followed by a note that the post-processor probably belongs to a plugin. The uses are detailed in the lesson Packer post-processors.

Which commands make up the Packer workflow?

The workflow boils down to three commands to run in this order. The first installs the plugins, the second checks the template, the third builds the image.

  1. Install the plugins with packer init

    This command reads the required_plugins block of the template and installs the missing plugins. Without it, the following commands fail with Missing plugins.

    Terminal window
    packer init .
  2. Check the template with packer validate

    This command checks the syntax and the references of the template. It creates no image.

    Terminal window
    packer validate .
  3. Build the image with packer build

    This command runs the builder, then the provisioners, then the post-processors.

    Terminal window
    packer build .

What does a Packer template look like?

An HCL2 template is a folder of .pkr.hcl files. It contains a packer block (required version and plugins), a source block (the builder and its starting image) and a build block (what you do with the source). The lesson HCL2 templates details these three blocks. Variables, which make the template configurable, are the subject of the lesson Variables and functions.

The template below starts from the Alpine Linux 3.24 image, pinned by its digest, and prints a message in it. It is run further down.

# packer block: minimum Packer version and required plugins
packer {
required_version = ">= 1.16.0"
required_plugins {
docker = {
version = "~> 1.1"
source = "github.com/hashicorp/docker"
}
}
}
# Source: the docker builder and the starting image
source "docker" "alpine" {
image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf"
commit = true
}
# Build: ties the source and the provisioners together
build {
name = "hello-packer"
sources = ["source.docker.alpine"]
provisioner "shell" {
inline = [
"echo '=========================================='",
"echo ' Félicitations ! Packer fonctionne !'",
"echo '=========================================='",
"cat /etc/os-release | grep PRETTY_NAME"
]
}
}

In the packer block, ~> 1.1 accepts any 1.x version of the plugin from 1.1 onward, and refuses a version 2. In the source, commit = true tells the docker builder to turn the container into an image at the end of the build: without it, validation fails with No instructions given for handling the artifact. The digest @sha256: pins the starting image: without it, the same alpine:3.24 can designate a different image from one day to the next.

What happens during a packer build?

A packer build follows the same steps whatever the builder. The output of the previous template shows them on a real build, where each line starts with ==> followed by the name of the build and of the source.

$ packer build .
hello-packer.docker.alpine: output will be in this color.
==> hello-packer.docker.alpine: Creating a temporary directory for sharing data...
==> hello-packer.docker.alpine: Pulling Docker image: alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
[...]
==> hello-packer.docker.alpine: Starting docker container...
==> hello-packer.docker.alpine: Run command: docker run -v /root/.config/packer/tmp3306999445:/packer-files -d -i -t --entrypoint=/bin/sh -- alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
==> hello-packer.docker.alpine: Container ID: 26d4496ebe428428f9b1ed99e8d339938cfcad893078a751dd9636c0e989bd65
==> hello-packer.docker.alpine: Provisioning with shell script: /tmp/packer-shell4032544036
==> hello-packer.docker.alpine: ==========================================
==> hello-packer.docker.alpine: Félicitations ! Packer fonctionne !
==> hello-packer.docker.alpine: ==========================================
==> hello-packer.docker.alpine: PRETTY_NAME="Alpine Linux v3.24"
==> hello-packer.docker.alpine: Committing the container
==> hello-packer.docker.alpine: Image ID: sha256:9b9039a3b153db68698ee574fbc971e910fbf107e4ea1824e67c5c7857c17f25
==> hello-packer.docker.alpine: Killing the container: 26d4496ebe428428f9b1ed99e8d339938cfcad893078a751dd9636c0e989bd65
Build 'hello-packer.docker.alpine' finished after 2 seconds 773 milliseconds.
==> Wait completed after 2 seconds 773 milliseconds
==> Builds finished. The artifacts of successful builds are:
--> hello-packer.docker.alpine: Imported Docker image: sha256:9b9039a3b153db68698ee574fbc971e910fbf107e4ea1824e67c5c7857c17f25

The diagram shows the six steps in order. The list that follows ties them to the lines of the output.

A packer build follows six steps in a row: the builder creates the temporary machine, Packer connects to it, the provisioners configure it, the builder freezes it into an image, the temporary machine is deleted, then Packer announces the artifact and the post-processors process it.packer buildThe builder createsthe temporary machinePacker connectsto the machineThe provisionersconfigure the machineThe builder freezesthe machine into an imageThe temporary machineis deletedPacker reports the artifact,post-processors handle it
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

Read the output from top to bottom, with these six steps:

  1. The builder creates the machine: it prepares a temporary folder, fetches the image (Pulling Docker image) and starts a container (Starting docker container).
  2. Packer connects to this machine. With the docker builder, it goes through Docker itself (docker exec). Virtual machine builders connect over SSH or WinRM, the Windows administration protocol.
  3. The provisioners run: here the shell script prints the four lines prefixed with ==> hello-packer.docker.alpine:.
  4. The builder freezes the machine into an image (Committing the container, then Image ID).
  5. The temporary machine is deleted (Killing the container).
  6. Packer announces the artifact (Imported Docker image). The post-processors, when the template declares some, work on this artifact.

The duration of the build (here under three seconds) depends on the image and the network: measure your own at the first build.

Packer, Ansible or Dockerfile: which one to choose?

Packer is sometimes confused with two families of tools. The distinction lies in when the tool acts: Packer configures before deployment and freezes the result in an image, a configuration manager such as Ansible acts on a machine that is already running, and a Dockerfile only produces container images.

AspectPackerAnsible, Chef, PuppetDockerfile
When it actsBefore deployment (build)During or after deploymentAt image build
ResultA frozen imageA configured machineA container image
TargetsVMs, cloud, containersExisting machinesContainers only

Packer and Ansible combine: Packer can call Ansible as a provisioner to build the image, then Ansible keeps handling light updates after deployment. For a simple container, the Dockerfile is enough. For VMs or images on several platforms, Packer is a better fit.

What are Packer's use cases?

Packer is useful wherever you want to start several identical machines from a reference image:

  • golden images for the cloud, for example an AMI preconfigured with the monitoring and security agents;
  • Proxmox or VMware templates for a homelab;
  • base Docker images that carry a team's standards;
  • identical development environments for all developers.

Which mistakes should you avoid at the start?

Four mistakes cost time or expose a secret. Knowing them saves you from discovering them in production.

The first is not installing the plugins. They do not install themselves: if you forget packer init, packer validate and packer build fail with Missing plugins followed by Did you run packer init for this project ?.

The second is not validating before building. packer validate catches a syntax error without creating anything, whereas a failed build wastes the time of the build.

The third is writing a secret in the template. A password written in a versioned file ends up in the Git history: pass it through an environment variable or a secrets vault.

The fourth is not reading the error message in full. Packer gives the file, the line and often the expected fix.

Key takeaways

Packer automates the creation of machine images from a versioned HCL template. Its code is available under the BSL license since version 1.10.0.

A build assembles three components in order: the builder creates the machine, the provisioners configure it, the post-processors process the artifact. The docker builder and provisioners such as ansible come from plugins, installed by packer init.

The workflow is packer init, packer validate, then packer build. A build creates a temporary machine, configures it, freezes it into an image, deletes it, then announces the artifact. A golden image is a validated reference image, and the starting image is pinned by its digest so that the build starts again from the same point.

Packer configures before deployment and freezes the result in an image, Ansible acts on a machine that is already running, and a Dockerfile only produces container images.

FAQ: frequently asked questions

Knowledge check

These questions cover what the lesson has just explained: the three components, the workflow and the steps of a build.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer