Packer is the HashiCorp tool that builds identical machine images from a single description file: a Docker image, an AWS AMI, an Azure, GCP or Proxmox image. This course takes you from your first template to a structured build chain, ready to plug into CI. The builder is the component that starts a temporary machine to produce the image: the examples use the Docker builder, with no cloud account and no cost.
It is aimed at developers, DevOps engineers, SREs and platform teams. It has
three prerequisites, which the course plan declares: Terraform (you have
already written HCL there, the language of Packer templates), Docker (the
builder used in every example) and Ansible (for the ansible provisioner
of the Provisioners lesson). The lessons do not teach these tools again: they
use them.
What will you be able to do at the end of the course?
At the end of the seven lessons, you will be able to:
- Explain what Packer builds and when to prefer it to a Dockerfile or to a configuration management tool;
- Install Packer on Linux and verify the downloaded binary;
- Write an HCL2 template and validate it with
packer fmt,packer validateandpacker inspect; - Parameterize that template with variables,
locals, functions and data sources; - Configure the image with the
shell,file,shell-localandansibleprovisioners, then chain post-processors; - Structure a project, protect its secrets and debug a build.
How is this course organized?
The modules follow one another in order. The second assumes that a first Docker build has succeeded, and the third reuses the parameterized template of the second. The table repeats the titles and durations of the course plan shown in the left-hand column.
| Module | Lessons | Duration | What you will be able to do |
|---|---|---|---|
| Discover Packer and run a first build | 2 | 1 h 05 | "I know why Packer exists, it is installed and I have built a first Docker image" |
| Write a parameterized HCL2 template | 2 | 1 h | "I write a clean HCL2 template and parameterize it with variables, locals and functions" |
| Configure the image and industrialize the build chain | 3 | 2 h | "I configure my images with shell, file or Ansible, I chain post-processors and I can plug my templates into CI" |
Each lesson ends with a 6-question quiz, drawn from a bank of 12 questions per lesson. There is no lab: the quizzes are the only validation mechanism of the course.
Discover Packer and run a first build
The first module lays the foundations and ends with an image that really exists. The Concepts and architecture lesson (25 min) explains why Packer exists, what a golden image is (a reference image, built once and reused as is to create identical machines), and how the builders, provisioners and post-processors chain together in a build. It also says when to prefer Packer to a Dockerfile or to Ansible.
The Install Packer and run a first build
lesson (40 min) installs Packer on Linux, through the APT repository, the DNF
repository, the zip archive whose checksum you verify with sha256sum -c, or
mise. For macOS and Windows, it points to the official documentation. It
checks the version, then builds a first Docker image from end to end.
mise is useful when your projects need different versions of Packer: a
.mise.toml file pins the version of each project. Once mise is installed (the
lesson points to its guide), installing Packer takes a single command:
mise use -g packer@1.16.2mise ✓ packer@1.16.2 5.3s packer_1.16.2_linux_amd64.zipmise ████████████████ 1/1 · installed 1 tool in 5.3smise ~/.config/mise/config.toml tools: packer@1.16.2The output confirms that mise downloaded the Linux archive of Packer 1.16.2 and recorded it in its global configuration.
How do you write a Packer HCL2 template?
The heart of Packer is the HCL2 templates, files named .pkr.hcl. The
Packer HCL2 templates
lesson (25 min) details their structure: the packer, source and build
blocks, splitting a template into several files, and the fmt, validate and
inspect commands that catch errors before the build. The
Packer variables, locals and functions
lesson (35 min) then makes the template flexible: input variables, locals,
.pkrvars.hcl files, data sources and built-in functions, so that you stop
copying a template for each environment.
The template below is the one from the Concepts and Install lessons, without
their shell provisioner. The packer block requires Packer 1.16.0 or later
and declares the docker plugin. The source starts from an Alpine image pinned
by its digest, and commit = true asks the builder to commit the container
as an image at the end. The build block references the source; the lessons
add provisioners and post-processors to it.
packer { required_version = ">= 1.16.0"
required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } }}
source "docker" "alpine" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true}
build { name = "hello-packer" sources = ["source.docker.alpine"]}The @sha256:… digest pins the exact content of the starting image: without
it, the same alpine:3.24 can point to a different image from one month to the
next.
How do you configure the image and industrialize the build?
The last module installs the system in the image, transforms the artifact that
was produced, then prepares the move to production. The
Packer provisioners
lesson (40 min) shows how to configure the temporary machine that the
builder starts: the shell, file, shell-local and ansible provisioners
run on it, before the builder freezes it into an image.
The Packer post-processors lesson (35 min) acts after the build, on the resulting artifact. The table gives the idea of each post-processor; the lesson details their options and chains them.
| Post-processor | Result |
|---|---|
compress | Archive of the image, in the format given by the extension (.tar.gz, .zip, .lz4...) |
manifest | JSON file with the build metadata |
checksum | Checksums, chosen by checksum_types (md5, sha256, etc.) |
docker-import | Import of the artifact into Docker Engine |
docker-tag | Additional tag on the Docker image |
docker-push | Push to a registry, with authentication; the lesson pushes two tags (the version and latest) to a local private registry |
The
Packer best practices
lesson (45 min) industrializes the templates: project layout, Makefile, secrets
management (through PKR_VAR_ environment variables, never in the template),
debugging and CI integration. For debugging, PACKER_LOG turns on Packer's
trace, and -debug runs the build step by step: the pause requires an
interactive terminal.
Where should you start?
Follow the lessons in order, starting with the concepts, and replay the Docker examples of each module.
First lesson: Packer concepts and architecture
If you already know Packer, go straight to the Variables and functions lesson or to the Provisioners lesson.
Recommended lesson: Packer variables, locals and functions
Go directly to the best practices to structure your projects and prepare CI integration.
Recommended lesson: Packer best practices
FAQ: frequently asked questions
The questions most often asked about Packer: difference with a Dockerfile or with Terraform, license, installation, provisioners and CI/CD integration. Packer has been distributed under the BSL license (Business Source License, identifier BUSL-1.1) since version 1.10.0.
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.Additional resources
Keep these addresses at hand during the course. The official documentation and the HCL2 reference answer most syntax questions, the integrations page lists the plugins available for each platform, and the HashiCorp FAQ covers troubleshooting cases.
- Official site: packer.io
- Documentation: developer.hashicorp.com/packer/docs
- HCL2 reference: developer.hashicorp.com/packer/docs/templates/hcl_templates
- Builders: developer.hashicorp.com/packer/integrations
- HashiCorp FAQ: developer.hashicorp.com/packer/docs/faq
- Packer on GitHub: github.com/hashicorp/packer