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,sourceandbuildof a template. - Read the steps of a
packer buildin 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.
| Aspect | Without Packer | With Packer |
|---|---|---|
| Image creation | Manual installation, clicks in an interface | One command: packer build |
| Reproducibility | "It worked last time" | The same description at every build |
| Documentation | Personal notes, outdated wiki | The HCL template describes the image |
| Several platforms | Redo the work for each target | One template, several sources |
| History | Hard to trace | Template 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 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.
| Builder | Platform | Typical use |
|---|---|---|
amazon-ebs | AWS | AMI for EC2 |
azure-arm | Azure | Managed images |
googlecompute | GCP | Compute Engine images |
qemu | KVM, libvirt | Local Linux images |
proxmox-iso | Proxmox | VM templates |
docker | Docker | Container images |
virtualbox-iso | VirtualBox | Developer 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.
| Provisioner | Role | Built into Packer |
|---|---|---|
shell | Runs shell commands or scripts | Yes |
file | Copies files into the image | Yes |
powershell | Runs PowerShell scripts (Windows) | Yes |
ansible | Runs an Ansible playbook | No, plugin required |
chef-solo, chef-client | Run Chef | No, plugin required |
puppet-masterless, puppet-server | Run Puppet | No, 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-processor | Action | Built into Packer |
|---|---|---|
manifest | Writes a JSON file describing the build | Yes |
compress | Compresses the artifact into an archive | Yes |
checksum | Computes a checksum | Yes |
docker-tag, docker-push | Tag and publish a Docker image | No, docker plugin |
vagrant | Converts to a Vagrant box | No, 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.
-
Install the plugins with
packer initThis command reads the
required_pluginsblock of the template and installs the missing plugins. Without it, the following commands fail withMissing plugins.Terminal window packer init . -
Check the template with
packer validateThis command checks the syntax and the references of the template. It creates no image.
Terminal window packer validate . -
Build the image with
packer buildThis 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 pluginspacker { required_version = ">= 1.16.0"
required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } }}
# Source: the docker builder and the starting imagesource "docker" "alpine" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true}
# Build: ties the source and the provisioners togetherbuild { 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: 26d4496ebe428428f9b1ed99e8d339938cfcad893078a751dd9636c0e989bd65Build '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:9b9039a3b153db68698ee574fbc971e910fbf107e4ea1824e67c5c7857c17f25The diagram shows the six steps in order. The list that follows ties them to the lines of the output.
Read the output from top to bottom, with these six steps:
- The builder creates the machine: it prepares a temporary folder, fetches the
image (
Pulling Docker image) and starts a container (Starting docker container). - Packer connects to this machine. With the
dockerbuilder, it goes through Docker itself (docker exec). Virtual machine builders connect over SSH or WinRM, the Windows administration protocol. - The provisioners run: here the
shellscript prints the four lines prefixed with==> hello-packer.docker.alpine:. - The builder freezes the machine into an image (
Committing the container, thenImage ID). - The temporary machine is deleted (
Killing the container). - 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.
| Aspect | Packer | Ansible, Chef, Puppet | Dockerfile |
|---|---|---|---|
| When it acts | Before deployment (build) | During or after deployment | At image build |
| Result | A frozen image | A configured machine | A container image |
| Targets | VMs, cloud, containers | Existing machines | Containers 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
What Packer does
| Function | Example |
|---|---|
| Image creation | AWS AMI, Docker images, Azure VMs |
| Multi-platform | 1 template → several images |
| Automation | Reproducible build with no intervention |
| Golden images | Standardized base image |
Quick example
This excerpt assumes thedocker plugin is declared in a packer { required_plugins { ... } } block and installed by packer init (see the question on HCL2).source "docker" "ubuntu" {
image = "ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8"
commit = true
}
build {
sources = ["source.docker.ubuntu"]
provisioner "shell" {
inline = ["apt-get update && apt-get install -y curl"]
}
}
Comparison
| Criterion | Packer | Dockerfile |
|---|---|---|
| Target | Multi-platform | Docker only |
| Format | HCL2 | Specific DSL |
| Configuration | Provisioners: shell, file, Ansible (plugin)... | RUN, COPY, ADD... instructions |
| Output | AMI, VMDK, OCI, Docker... | Docker image |
| Ecosystem | HashiCorp | Docker/OCI |
| Use case | Multi-cloud golden images | Application containers |
When to use which?
- Dockerfile: containerized applications, local development
- Packer: multi-cloud golden images, immutable infrastructure
- Both: Packer can use Docker as a test builder
Identical example
# Dockerfile
FROM ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8
RUN apt-get update && apt-get install -y curl
# Packer HCL2 (excerpt, docker plugin declared in required_plugins)
source "docker" "ubuntu" {
image = "ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8"
commit = true
}
build {
sources = ["source.docker.ubuntu"]
provisioner "shell" {
inline = ["apt-get update && apt-get install -y curl"]
}
}
Linux
# With mise (version manager)
mise use -g packer@1.16.2
# Or zip archive, verifying the checksum before installing
V=1.16.2
curl -fsSL -O https://releases.hashicorp.com/packer/${V}/packer_${V}_linux_amd64.zip
curl -fsSL -O https://releases.hashicorp.com/packer/${V}/packer_${V}_SHA256SUMS
grep linux_amd64 packer_${V}_SHA256SUMS | sha256sum -c -
unzip packer_${V}_linux_amd64.zip
sudo mv packer /usr/local/bin/
The HashiCorp APT or DNF repository is the other route on Linux: the lessonInstall Packer
details each method.
macOS and Windows
Follow the official installation page,developer.hashicorp.com/packer/install.
Check
packer --version
# Packer v1.16.2
.pkr.hcl file that defines how to build an image.Main blocks
| Block | Role | Required |
|---|---|---|
packer {} |
Configuration, required plugins | Optional |
source |
Builder definition | Yes |
build |
Build orchestration | Yes |
variable |
Input parameters | Optional |
locals |
Computed values | Optional |
Minimal example
packer {
required_plugins {
docker = {
version = "~> 1.1"
source = "github.com/hashicorp/docker"
}
}
}
source "docker" "ubuntu" {
image = "ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8"
commit = true
}
build {
sources = ["source.docker.ubuntu"]
}
HCL2 vs JSON
| Aspect | HCL2 | JSON (legacy) |
|---|---|---|
| Readability | Excellent | Hard |
| Comments | # or // |
Not supported |
| Functions | Built-in | Limited |
| Status | Recommended | Old format |
packer hcl2_upgrade converts it to HCL2.Validation workflow
# 1. Download the required plugins
packer init .
# 2. Check the formatting
packer fmt -check .
# 3. Validate the syntax and consistency
packer validate .
# Optional: with variables
packer validate -var "base_image=ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8" .
What Packer checks
| Command | Checks |
|---|---|
packer init |
Plugins available and downloaded |
packer fmt -check |
HCL formatting is compliant |
packer validate |
Syntax, references, consistency |
In CI/CD
# Fail at the first problem
packer init . && packer fmt -check . && packer validate .
Example output
$ packer validate .
The configuration is valid.
# An invalid template stops with an Error: message
# and a non-zero exit code.
Main builders
| Builder | Platform | Output |
|---|---|---|
| docker | Docker Engine | Docker image (or tar archive with export_path) |
| amazon-ebs | AWS | AMI |
| azure-arm | Azure | Managed Image |
| googlecompute | GCP | Compute Image |
| qemu | KVM | QCOW2 |
| proxmox-iso | Proxmox VE | VM template |
| vmware-iso | VMware | VMDK |
| virtualbox-iso | VirtualBox | OVF |
| lxc / lxd | Linux containers | LXC/LXD image |
| null | Test | No image (provisioners run on an existing machine) |
Installing the plugins
packer {
required_plugins {
docker = {
version = "~> 1.1"
source = "github.com/hashicorp/docker"
}
amazon = {
version = "~> 1.1"
source = "github.com/hashicorp/amazon"
}
}
}
Multi-platform
A single template can target several builders:build {
sources = [
"source.docker.ubuntu",
"source.amazon-ebs.ubuntu"
]
}
Declaration
variable "base_image" {
type = string
default = "ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8"
description = "Image de départ, épinglée par son digest"
}
variable "image_tag" {
type = string
default = "1.0.0"
description = "Version de l'image produite"
}
variable "packages" {
type = list(string)
default = ["curl", "wget", "vim"]
}
Usage
source "docker" "app" {
image = var.base_image
commit = true
}
Providing values
| Method | Example |
|---|---|
| CLI | packer build -var "image_tag=1.0" . |
| File | packer build -var-file=prod.pkrvars.hcl . |
| Environment | export PKR_VAR_image_tag=1.0 |
Locals (computed values)
locals {
timestamp = formatdate("YYYYMMDDhhmmss", timestamp())
image_name = "app-${var.image_tag}-${local.timestamp}"
}
Main provisioners
| Provisioner | Use |
|---|---|
| shell | bash/sh commands, scripts |
| file | Copy files into the image |
| ansible | Run playbooks (plugin to declare) |
| shell-local | Commands on the host machine |
Example
build {
sources = ["source.docker.ubuntu"]
provisioner "file" {
source = "config/app.conf"
destination = "/tmp/app.conf"
}
provisioner "shell" {
inline = [
"apt-get update",
"apt-get install -y nginx",
"mkdir -p /etc/app",
"mv /tmp/app.conf /etc/app/app.conf"
]
}
}
The file provisioner requires a destination folder that already exists: thefile therefore goes through
/tmp, then the shell puts it away in /etc/app.Execution order
Provisioners run in the order of declaration:file copies the file, thenshell installs the packages and puts it away. The ansible provisioner comesfrom a plugin: it is declared in
required_plugins, and Ansible must beinstalled on the machine that runs Packer (lesson
Provisioners, in
French).
Detailed logs
# Enable all the logs
export PACKER_LOG=1
packer build .
# Or in one line
PACKER_LOG=1 packer build .
Interactive mode
# Step by step: the pause depends on the builder and needs an interactive terminal
packer build -debug .
# Log to a file
PACKER_LOG=1 PACKER_LOG_PATH=packer.log packer build -debug .
Without a terminal, in a CI job for example, -debug does not stop: PACKER_LOG=1 and -on-error=abort are more useful there.Error handling
# Ask what to do on error
packer build -on-error=ask .
# Options: abort, retry, cleanup
Common problems
| Symptom | Likely cause |
|---|---|
| SSH timeout | Firewall, wrong SSH key |
| Command not found | Path not in PATH |
| Permission denied | Non-root user, sudo required |
Missing plugins |
packer init . not run |
Error: Unset variable |
Variable declared with no value and no default |
Error: Undefined -var variable |
-var cites a variable that is not declared |
Warning: Undefined variable |
A value file defines a variable that is not declared |
Main post-processors
| Post-processor | Action |
|---|---|
| compress | .tar.gz archive of the image |
| manifest | JSON file with metadata |
| checksum | Checksums (md5, sha256...) chosen by checksum_types |
| docker-import | Import into Docker Engine |
| docker-tag | Add tags to the image |
| docker-push | Push to a registry |
Simple example
build {
sources = ["source.docker.ubuntu"]
post-processor "manifest" {
output = "manifest.json"
}
}
Chaining post-processors
# To place inside the build block
post-processors {
post-processor "docker-import" {
repository = "registry.mon-entreprise.fr/myapp"
tag = "1.0.0"
}
post-processor "docker-push" {
login = true
login_server = "registry.mon-entreprise.fr"
login_username = var.registry_user
login_password = var.registry_pass # variable declared with sensitive = true
}
}
Chaining guarantees that each step uses the result of the previous one. The registry name is part of repository: without it, the image would go to Docker Hub. docker-import expects a source that exports the container (export_path), as in the lesson Post-processors.packer init, packer fmt -check, packer validate, then packer build.GitHub Actions
name: Build Image
on: [push]
permissions: {}
jobs:
packer:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Packer
uses: hashicorp/setup-packer@ce93c3c08a6c2ff2275bf4b54ff0d9a75f6c9789 # v3.4.0
with:
version: "1.16.2"
- name: Init
run: packer init .
- name: Validate
run: packer fmt -check . && packer validate .
- name: Build
run: packer build .
env:
PKR_VAR_image_tag: ${{ github.sha }}
GitLab CI/CD
packer-build:
image:
name: hashicorp/packer:1.16.2@sha256:5aa2160b623fad0b99f8ae8d9cc162ba9775ae428367edca88addc01bb86dd52
# The image starts on /bin/packer: we empty the entrypoint so that GitLab runs script
entrypoint: [""]
script:
- packer init .
- packer fmt -check .
- packer validate .
- packer build .
variables:
PKR_VAR_image_tag: $CI_COMMIT_SHORT_SHA
PACKER_PLUGIN_PATH: $CI_PROJECT_DIR/.packer-plugins
cache:
paths:
- .packer-plugins/
The hashicorp/packer image contains neither the Docker client nor the Dockerdaemon: this example suits a cloud source. With a
docker source, add theDocker-in-Docker service and a Docker client, as in the lesson
Best practices.
CI/CD best practices
- Cache the plugins directory (
~/.config/packer/pluginsby default, changeable withPACKER_PLUGIN_PATH) - Environment variables for secrets
- Validation before the build
- Manifest for traceability
amazon-ebs builder.Minimal template
packer {
required_plugins {
amazon = {
version = "~> 1.1"
source = "github.com/hashicorp/amazon"
}
}
}
variable "aws_region" {
default = "eu-west-3"
}
locals {
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
}
source "amazon-ebs" "ubuntu" {
region = var.aws_region
instance_type = "t3.micro"
source_ami_filter {
filters = {
name = "ubuntu/images/*ubuntu-noble-24.04-amd64-server-*"
root-device-type = "ebs"
virtualization-type = "hvm"
}
most_recent = true
owners = ["099720109477"] # Canonical
}
ssh_username = "ubuntu"
ami_name = "my-app-${local.timestamp}"
}
build {
sources = ["source.amazon-ebs.ubuntu"]
provisioner "shell" {
inline = ["sudo apt-get update && sudo apt-get install -y nginx"]
}
}
Authentication
# AWS profile configured beforehand (aws configure sso), with no key typed in the shell
export AWS_PROFILE=packer-build
packer build .
The build starts an EC2 instance billed for the duration of the build, then theAMI and its EBS snapshot stay billed until you delete them (deregister the AMI,
then delete the snapshot).
Folder tree
projet-packer/
├── packer.pkr.hcl # Packer version and plugins
├── common.pkr.hcl # Variable declarations
├── locals.pkr.hcl # Computed values
├── docker.pkr.hcl # Docker sources
├── build.pkr.hcl # Build blocks
├── dev.auto.pkrvars.hcl # Dev values, loaded automatically
├── variables/
│ └── prod.pkrvars.hcl # Prod values, passed by -var-file
├── scripts/
│ └── setup-common.sh
└── Makefile
Makefile
.PHONY: init validate build build-dev build-prod clean
init:
packer init .
validate: init
packer fmt -check .
packer validate .
build: validate
packer build .
build-dev: validate
packer build -only="*.dev" .
build-prod: validate
packer build -var-file=variables/prod.pkrvars.hcl -only="*.prod" .
clean:
rm -rf output/* manifest*.json *.checksum packer_cache/
Usage
make build # All the sources
make build-dev # Dev source
make build-prod # Prod source
The -only="*.dev" and -only="*.prod" filters assume sources named dev and prod (source "docker" "dev"). A *.auto.pkrvars.hcl file is only loaded automatically at the rootof the project, never in a subfolder. The lesson
Best practices details this structure.
Sensitive variables
variable "docker_password" {
type = string
sensitive = true # Replaced by <sensitive> in Packer's display
}
Packer replaces the value with <sensitive> in packer inspect and in the output of a packer build, including when a shell script prints it. The masking only applies to the display: the template and the scripts read the real value. With a very short secret, pieces of other messages are masked too: choose long values.Best practices
| Method | Security | Use |
|---|---|---|
| Env vars | Good | read -rs PKR_VAR_password && export PKR_VAR_password (hidden input) |
| CI Secrets | Excellent | GitHub Secrets, GitLab CI Variables |
| Vault | Enterprise | HashiCorp Vault integration |
| CLI -var | Risky | Visible in shell history |
| Committed file | Dangerous | Never in production |
In CI/CD
# GitHub Actions
env:
PKR_VAR_docker_password: ${{ secrets.DOCKER_PASSWORD }}
# GitLab CI
variables:
PKR_VAR_docker_password: $DOCKER_PASSWORD
.gitignore
# Secrets file, never committed
secrets.pkrvars.hcl
Value files with no secret (dev.auto.pkrvars.hcl,variables/prod.pkrvars.hcl) stay versioned: the CI needs them.Multi-source
Excerpt, without thepacker block that declares the docker and amazon plugins:source "docker" "app" {
image = "ubuntu:24.04@sha256:73b999393d07f2bf65a40373778a44dc9a6d54ad7718d29247d8ff9413c4d6a8"
commit = true
}
source "amazon-ebs" "app" {
region = "eu-west-3"
instance_type = "t3.micro"
# ...
}
build {
sources = [
"source.docker.app",
"source.amazon-ebs.app"
]
provisioner "shell" {
inline = ["echo 'Hello from ${source.type}'"]
}
}
Controlling parallelism
# Limit to 2 simultaneous builds
packer build -parallel-builds=2 .
# One build at a time
packer build -parallel-builds=1 .
Benefits
- Time saved: Docker and AWS build at the same time
- Same configuration: shared provisioners
- Separate artifacts: each builder produces its image
| Criterion | Packer | Terraform |
|---|---|---|
| Role | Build machine images | Provision infrastructure |
| Produces | AMI, Docker image, QCOW2, VMDK | VM, network, storage, DNS |
| When | Before deployment (build) | At deployment (apply) |
| Language | HCL2 | HCL2 |
Combined workflow
- Packer builds a hardened, preconfigured image (golden image).
- Terraform deploys instances from this image.
License
Since version 1.10.0, Packer is distributed under BUSL-1.1 (Business Source License), replacing the historical MPL-2.0 license. In practice:- Use stays free and at no cost to build your images, including in companies and in CI/CD.
- The only restriction targets commercially competing with HashiCorp products, which does not concern teams that use Packer for their own needs.
| Aspect | Packer | Vagrant |
|---|---|---|
| Goal | Build machine images | Orchestrate dev VMs |
| Target | Production, cloud, multi-platform | Local development workstation |
| Produces | AMI, Docker image, QCOW2, box | VM started from a box |
| Lifecycle | One-off build of an artifact | up, ssh, halt, destroy |
How they fit together
Packer can generate the boxes that Vagrant consumes, thanks to thevagrant post-processor, provided by the github.com/hashicorp/vagrant plugin to declare in required_plugins:post-processor "vagrant" {
output = "ma-box.box"
}
In practice: Packer standardizes the base image once and for all, Vagrant instantiates it locally so that each developer works in the same environment.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
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
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Install Packer and run a first build
A new full quiz with random questions
Work again only on the questions you missed