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

By updated

Improve this page

Logo Packer

A growing Packer project quickly becomes unreadable: a single file of several hundred lines, secrets in the Git history, builds that pass on one workstation and fail in CI. This lesson is for anyone who can write a template, provisioners and post-processors, and wants a maintainable and automated project. You will organize the files, protect the secrets, debug a failing build and plug the project into GitHub Actions or GitLab CI.

What you will learn

  • Organize a Packer project into files that each carry one responsibility.
  • Choose version constraints that accept fixes without accepting breaking changes, name your files and know which variable files Packer loads by itself.
  • Pass and protect secrets.
  • Debug a failing build, with PACKER_LOG, -debug and -on-error.
  • Validate and build in GitHub Actions, GitLab CI or a Makefile.
  • Build several images in one run and start from a local base image.

Prerequisites

Why good practices are essential

A Packer project starts small, then environments (dev, staging, prod), providers and secrets pile up. Without conventions, each change costs more than the previous one. The table links each problem to what it causes and to the remedy the lesson details.

ProblemSymptomRemedy
Monolithic codeA single file of more than 500 linesOne file per responsibility
DuplicationCopy-pasted sourcesVariables and locals
Exposed secretsPassword in the Git historySensitive variables and a strict .gitignore
Non-reproducible build"It works on my machine"Constrained Packer and plugin versions, pinned images
Hard debuggingError without contextPACKER_LOG, -debug, -on-error

The structure separates responsibilities: Packer reads every file with a .pkr.hcl suffix in the folder as a single set, so the file names are for finding things, not for ordering them.

  • Répertoiremy-packer-project/
    • packer.pkr.hcl
    • docker.pkr.hcl
    • common.pkr.hcl
    • locals.pkr.hcl
    • build.pkr.hcl
    • dev.auto.pkrvars.hcl
    • Répertoirevariables/
      • prod.pkrvars.hcl
    • Répertoirescripts/
      • setup-common.sh
      • validate.sh
    • Répertoirefiles/
      • …
    • Répertoireoutput/
      • …
    • .gitignore
    • Répertoire.github/workflows/
      • packer-build.yml
    • Makefile

The table gives the role of each element. The dev.auto.pkrvars.hcl file is at the root: Packer automatically loads only the *.auto.pkrvars.hcl files of the current folder, not those of a subfolder.

ElementRole
packer.pkr.hclPacker version and plugins
docker.pkr.hclDocker sources (one file per builder type)
common.pkr.hclVariables, with description and validation
locals.pkr.hclValues computed from the variables
build.pkr.hclThe build block, its provisioners and post-processors
dev.auto.pkrvars.hclDevelopment values, loaded without any option
variables/prod.pkrvars.hclProduction values, loaded by -var-file
scripts/, files/Provisioning scripts and files to upload
output/Generated artifacts, ignored by Git

The packer.pkr.hcl file

This file declares the accepted Packer version and the plugins. It is the first one read by someone discovering the project.

packer.pkr.hcl
packer {
required_version = "~> 1.16"
required_plugins {
docker = {
version = "~> 1.1"
source = "github.com/hashicorp/docker"
}
}
}

The ~> operator lets only the last number given in the constraint go up. ~> 1.16 lets the 16 go up: it accepts 1.16.2 and 1.17.0, and rejects 2.0.0. With three numbers, the trap is tighter than it looks: ~> 1.15.0 accepts only 1.15.x, so it rejects Packer 1.16.2, and validation fails.

Error: Unsupported Packer Core version
on packer.pkr.hcl line 2, in packer:
2: required_version = "~> 1.15.0"
This configuration does not support Packer version 1.16.2. To proceed, either
choose another supported Packer version or update this version constraint.

A >= 1.10.0 constraint accepts 1.16.2 without error, but it would also accept a future 2.x version that might break the template. For a plugin, ~> 1.1 strikes the same compromise: the fixes and new features of the 1 series, never the 2.

The sources file

One file per builder type keeps each source readable. The three sources share a single base image, pinned by digest, defined in a variable: changing the image is done in one place.

docker.pkr.hcl
# Development: image kept in Docker, with metadata
source "docker" "dev" {
image = var.base_image
commit = true
changes = [
"ENV APP_ENV=development",
"ENV APP_VERSION=${var.app_version}",
"LABEL org.opencontainers.image.version=${var.app_version}",
"LABEL org.opencontainers.image.environment=development"
]
}
# Staging: same base image, kept in Docker
source "docker" "staging" {
image = var.base_image
commit = true
}
# Production: image exported to a file for distribution
source "docker" "prod" {
image = var.base_image
export_path = "${var.output_dir}/${var.app_name}-prod-${var.app_version}.tar"
}

The staging source is nothing special, but the build block of the "The build file" section cites it. A build that cites a missing source fails validation with Unknown source docker.staging, followed by the list of known sources.

The variables file

All the variables live in one file, with a description and, when useful, a validation. It is the documentation of the project: you read the expected values without opening the rest. The build_number and git_commit variables are declared so that CI can pass them: a variable passed on the command line but not declared is rejected (the CI section comes back to this).

common.pkr.hcl
variable "app_name" {
type = string
description = "Nom de l'application (utilisé dans les tags et noms d'images)"
default = "mywebapp"
validation {
condition = can(regex("^[a-z][a-z0-9-]*$", var.app_name))
error_message = "Le nom doit commencer par une lettre minuscule et ne contenir que des caractères alphanumériques et des tirets."
}
}
variable "app_version" {
type = string
description = "Version de l'application (semver recommandé)"
default = "1.0.0"
validation {
condition = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+(-[a-z0-9]+)?$", var.app_version))
error_message = "La version doit suivre le format semver (ex: 1.2.3 ou 1.2.3-beta)."
}
}
variable "environment" {
type = string
description = "Environnement cible (dev, staging, prod)"
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "L'environnement doit être 'dev', 'staging' ou 'prod'."
}
}
variable "base_image" {
type = string
description = "Image de base, épinglée par digest"
default = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf"
}
variable "output_dir" {
type = string
description = "Dossier des artefacts exportés"
default = "output"
}
variable "build_number" {
type = string
description = "Numéro de build, fourni par la CI"
default = "local"
}
variable "git_commit" {
type = string
description = "Commit construit, fourni par la CI"
default = "none"
}
variable "registry_password" {
type = string
description = "Mot de passe du registre Docker (ne jamais commiter)"
default = ""
sensitive = true
}

A failing validation stops the command before any build, and the message names the rule. With packer validate -var app_name=Bad ., Packer answers:

Error: Invalid value for cmd variable
on line 0:
(source code not available)
Le nom doit commencer par une lettre minuscule et ne contenir que des caractères
alphanumériques et des tirets.
This was checked by the validation rule at common.pkr.hcl:6,3-13.

The same check rejects -var app_version=1.0 (not in semver format) and -var environment=test (outside the list), and accepts -var app_version=1.2.3-beta.

The locals file

The locals centralize the values derived from the variables: full version, artifact name, tags. They avoid repeating a computation in several places.

locals.pkr.hcl
locals {
# Compact timestamp for artifact names
timestamp = regex_replace(timestamp(), "[- TZ:]", "")
# Short date for labels
build_date = formatdate("YYYY-MM-DD", timestamp())
# Full version with the CI build number
full_version = var.build_number != "local" ? "${var.app_version}-${var.build_number}" : var.app_version
# Base name of the artifacts
artifact_name = "${var.app_name}-${local.full_version}"
# Docker tags, with no duplicate or null value
docker_tags = distinct(compact([
local.full_version,
var.app_version,
var.environment == "prod" ? "latest" : null,
"${var.environment}-latest"
]))
}

To see these values, print them with a shell-local provisioner in a test build named show. In development (build_number at local), full_version and app_version are identical: without distinct, the list would contain 1.0.0 twice. With the locals above, the output is:

==> show.docker.dev: fullv=1.0.0
==> show.docker.dev: tags=1.0.0,dev-latest

The compact function removes the null values (the latest tag exists only in production), and distinct removes duplicates. With -var environment=prod -var build_number=9, the list becomes 1.0.0-9,1.0.0,latest,prod-latest.

The build file

The build block cites the three sources, chains a common provisioner and two provisioners specific to one source. The only attribute is aligned with inline there: packer fmt -check otherwise reports a badly formatted block.

build.pkr.hcl
build {
name = "app-build"
sources = [
"source.docker.dev",
"source.docker.staging",
"source.docker.prod"
]
provisioner "shell" {
scripts = ["scripts/setup-common.sh"]
}
provisioner "shell" {
only = ["docker.dev"]
inline = ["apk add --no-cache vim htop strace"]
}
provisioner "shell" {
only = ["docker.prod"]
inline = ["rm -rf /var/cache/apk/* /tmp/*"]
}
}

The scripts and the output folder must exist before the build: mkdir -p scripts output, then a scripts/setup-common.sh file that contains, to begin with, echo setup-common-ok. Validation of the project then succeeds:

$ packer validate .
The configuration is valid.

You still have to write the two values files and the validation script. The dev.auto.pkrvars.hcl file, at the root, chooses the development environment:

dev.auto.pkrvars.hcl
environment = "dev"

The variables/prod.pkrvars.hcl file sets the production environment and the version. It is loaded only with -var-file=variables/prod.pkrvars.hcl:

variables/prod.pkrvars.hcl
environment = "prod"
app_version = "1.0.0"

The scripts/validate.sh script serves as an example for the section on the validation provisioner. Its content makes the build fail on purpose:

scripts/validate.sh
echo verif; exit 1

Naming conventions

Consistent names make files predictable. The three tables gather the conventions of the lesson.

Variables and locals

A variable name says its domain then its role, in snake_case, and each variable carries a description: that is what makes the variables file readable on its own.

ElementConventionExample
Variablessnake_caseapp_version, build_number
Domain prefixdomain_nameapp_name, registry_password
DescriptionsAlways filled indescription = "..."

Sources and builds

The name of a source says what it is for, and that of a build says what it builds. It is this name that -only and -except target, as you will see below.

ElementConventionExample
Source namesOne name per roledocker.dev, docker.prod
Build namesDescriptivename = "app-build"
Environmentsdev, staging, prodsource.docker.prod

Files

The suffix of a file decides its role: .pkr.hcl for a template, .auto.pkrvars.hcl for values loaded without an option, .pkrvars.hcl for values passed with -var-file.

ElementConventionExample
Templates.pkr.hclbuild.pkr.hcl
Self-loaded variables.auto.pkrvars.hcl, at the rootdev.auto.pkrvars.hcl
Variables loaded on demand.pkrvars.hcl, with -var-filevariables/prod.pkrvars.hcl
Scriptskebab-casesetup-common.sh

A variables/dev.auto.pkrvars.hcl file that defines app_name is not loaded, and the build prints the default value (app_name=mywebapp). The same file placed at the root is loaded (app_name=racine), and a variables/prod.pkrvars.hcl file given with -var-file is taken into account (app_name=prodfile).

Secret management

A secret in the Git history compromises everything it protects. The rule is to never write it in a file tracked by Git.

Core rules

These four rules cover the essentials.

  1. Never commit a secret

    Neither in the files, nor in the commit messages.

  2. Declare the variable with sensitive = true

    Packer then masks its value in the logs.

  3. Prefer environment variables

    A secret passed through the environment is written nowhere in the project.

  4. Keep a strict .gitignore

    Block secret files by pattern.

Environment variables

Packer reads the environment variables prefixed with PKR_VAR_. With PKR_VAR_registry_password and a sensitive variable, the secret stays usable by the build, but Packer replaces it with <sensitive> in the output.

Passing a secret through the environment
export PKR_VAR_registry_password="$(cat ~/.secrets/regpass)"
packer build .

The value is read from a file that only your account can read (chmod 600), as in the lesson on post-processors: a password written in the command would stay in the shell history.

To check the masking, this template prints the value twice: with a shell-local on your machine, then with a shell in the container, which receives the secret through environment_vars.

build.pkr.hcl
build {
sources = ["source.docker.alpine"]
provisioner "shell-local" {
inline = ["echo secret-vu=${var.registry_password}"]
}
provisioner "shell" {
inline = ["echo dans-limage=$PW"]
environment_vars = ["PW=${var.registry_password}"]
}
}

The two printed lines show the masked value:

==> docker.alpine: secret-vu=<sensitive>
[...]
==> docker.alpine: dans-limage=<sensitive>

The masking protects the logs, not the content of the image: a secret written to a file of the image by a provisioner stays there. Do not write secrets in the image.

For several secrets, a file that is not committed does the job. Create it with a text editor, not with an echo or cat command that would leave the values in the shell history. First create the empty file, reserved to your account, then fill it with the editor:

Terminal window
install -m 600 /dev/null secrets.pkrvars.hcl
secrets.pkrvars.hcl (added to .gitignore)
registry_password = "valeur-du-mot-de-passe"
aws_secret_key = "valeur-de-la-cle"
Terminal window
packer build -var-file=secrets.pkrvars.hcl .

If the file defines a variable that the template does not declare, Packer still validates, with a warning that names the variable:

Warning: Undefined variable
The variable "aws_secret_key" was set but was not declared as an input variable.
[...]

.gitignore for Packer

This .gitignore keeps artifacts, generated files and secret files out of the repository.

.gitignore
# Build artifacts
output/
*.tar
*.tar.gz
*.zip
*.ova
*.qcow2
# Generated files
packer_cache/
crash.log
manifest*.json
*.checksum
# Temporary SSH keys (cloud builders in debug mode)
*.pem
# Sensitive variables
*.secret.pkrvars.hcl
*-secret.pkrvars.hcl
secrets.pkrvars.hcl
# Local environments
.env
.env.local
*.local.pkrvars.hcl

Debugging builds

A build fails for various reasons: script, network, permissions, timeout. The three tools of this section answer three questions: what does Packer do (PACKER_LOG), where does it stop (-debug, depending on the builder), and what becomes of the machine after the failure (-on-error).

Detailed logs

The PACKER_LOG=1 variable enables Packer's logs on the error output, and PACKER_LOG_PATH writes them to a file.

Enable detailed logs
PACKER_LOG=1 packer build .
PACKER_LOG=1 PACKER_LOG_PATH=packer.log packer build .

These logs show the loaded plugins, the commands sent and the exchanges with the builder. Do not count on [ERROR] to spot the cause: on a provisioner that fails with exit 3, the log contains no [ERROR] line and only two [WARN] lines. The error of a script is read in the normal build output, on the Script exited with non-zero exit status: 3 line.

Debug mode

The -debug option puts builds in step-by-step mode: the Packer documentation says that builders generally pause between steps, waiting for the Enter key. The pause therefore depends on the builder. Packer announces the mode at launch and no longer runs builds in parallel:

$ packer build -debug .
Debug mode enabled. Builds will not be parallelized.

To wait for the Enter key, Packer needs an interactive terminal. In a real terminal, the docker builder pauses after each step, then before each of its cleanups, and resumes at each press of Enter:

$ packer build -debug .
Debug mode enabled. Builds will not be parallelized.
docker.app: output will be in this color.
==> docker.app: Pausing after run of step 'StepDefaultGeneratedData'. Press enter to continue.
==> docker.app: Creating a temporary directory for sharing data...
==> docker.app: Pausing after run of step 'StepTempDir'. Press enter to continue.
[...]
==> docker.app: Pausing after run of step 'StepRun'. Press enter to continue.
==> docker.app: Pausing after run of step 'StepConnect'. Press enter to continue.
==> docker.app: Pausing before the next provisioner . Press enter to continue.
[...]

Without a terminal, for example in a CI job or a script, no pause happens and the build runs to the end. In that case, PACKER_LOG=1 or -on-error=abort give more information than -debug.

With the docker builder, -debug writes no SSH key: there is no SSH connection to a machine. With a cloud builder, Packer creates a temporary key pair and saves the private key in the current folder, under the name of the source, before showing the address of the instance. This case depends on a cloud provider and is not shown here.

Connect to the paused instance (cloud builder)
chmod 600 oapi_builder
ssh -i oapi_builder outscale@217.75.166.255

The key name, the address and the user vary with the builder and the distribution. Add the names of these keys to .gitignore so as not to commit them.

The on-error option

The -on-error option says what becomes of the machine when a build fails. Four values are accepted, and the table gives the effect of each.

ValueEffect
cleanup (default)Packer destroys the machine, no container remains
abortPacker stops without cleaning up: the container stays (docker ps -a shows it)
askPacker asks what to do, at the terminal
run-cleanup-provisionerPacker plays the error-cleanup-provisioner block if it exists; without that block, it skips the cleanups as with abort

The run-cleanup-provisioner value retries nothing: it is used to launch the cleanup described in the template (see the lesson on provisioners). An unknown value is rejected with the list of values:

invalid value "bogus" for flag -on-error: expected one of ["cleanup" "abort" "ask" "run-cleanup-provisioner"]

With -on-error=abort, Packer announces that it skips each cleanup, step by step, and the machine stays alive so that you can inspect it:

==> docker.alpine: Step "StepProvision" failed, aborting...
==> docker.alpine: aborted: skipping cleanup of step "StepConnect"
==> docker.alpine: aborted: skipping cleanup of step "StepRun"
[...]

Common errors and solutions

The table gathers the errors this project can produce, with the message that lets you recognize them.

MessageCauseSolution
This configuration does not support Packer version 1.16.2required_version too tight (~> 1.15.0)Widen the constraint, for example ~> 1.16
Unknown source docker.stagingThe build cites an undefined sourceDefine the source, or remove it from the build
Unsupported attribute ... "build_number"Variable used without a declarationAdd the variable block
Undefined -var variable-var on an undeclared variableDeclare the variable, or remove the -var
Script exited with non-zero exit statusA provisioning script failsRead the last output of the script, replay it by hand
pull access denied for local/baseThe local base image does not exist yet, or the source tries to download itBuild the base image first, with its tag, and set pull = false in the source that consumes it

Validation provisioner

Put a validation provisioner at the end of the build: it checks the image before it is saved. If it fails, the build stops, and no faulty image is produced.

build.pkr.hcl (excerpt)
provisioner "shell" {
scripts = ["scripts/validate.sh"]
}

A script that fails (echo verif; exit 1) stops the build and announces it:

==> docker.alpine: Provisioning with shell script: scripts/validate.sh
==> docker.alpine: verif
==> docker.alpine: Provisioning step had errors: Running the cleanup provisioner, if present...
[...]
Build 'docker.alpine' errored after 2 seconds 82 milliseconds: Script exited with non-zero exit status: 1. Allowed exit codes are: [0]

The script checks what matters for your image: installed packages, permissions, configured services.

CI/CD integration

A pipeline replays the same sequence on every change: packer fmt -check, packer init, packer validate, then packer build on the main branch. The workflows below were not run: launch them on a test repository before adopting them.

Typical CI/CD workflow

The pipeline follows four steps.

  1. Validation

    packer fmt -check and packer validate on every merge request.

  2. Build

    packer build after the merge into the main branch.

  3. Publication

    Deposit of the artifacts in a registry or a storage.

  4. Notification

    Informing the team of the result.

GitHub Actions

This workflow validates on every merge request and builds after the merge into main. The actions are pinned on the commit SHA, with the version in a comment (the lesson Pinning actions by SHA explains why). The workflow grants no right to the token (permissions: {}), and each job asks only for read access to the contents (contents: read).

.github/workflows/packer-build.yml
name: Packer Build
on:
push:
branches: [main]
paths:
- "**.pkr.hcl"
- "**.pkrvars.hcl"
- "scripts/**"
pull_request:
branches: [main]
paths:
- "**.pkr.hcl"
permissions: {}
env:
PACKER_VERSION: "1.16.2"
jobs:
validate:
name: Validate Packer Templates
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Packer
uses: hashicorp/setup-packer@ce93c3c08a6c2ff2275bf4b54ff0d9a75f6c9789 # v3.4.0
with:
version: ${{ env.PACKER_VERSION }}
- name: Initialize Packer
run: packer init .
- name: Format check
run: packer fmt -check -diff .
- name: Validate templates
run: packer validate .
build:
name: Build Images
runs-on: ubuntu-latest
needs: validate
if: github.ref == 'refs/heads/main'
permissions:
contents: read
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Setup Packer
uses: hashicorp/setup-packer@ce93c3c08a6c2ff2275bf4b54ff0d9a75f6c9789 # v3.4.0
with:
version: ${{ env.PACKER_VERSION }}
- name: Initialize Packer
run: packer init .
- name: Build images
env:
PKR_VAR_build_number: ${{ github.run_number }}
PKR_VAR_git_commit: ${{ github.sha }}
PKR_VAR_environment: prod
run: |
mkdir -p output
packer build \
-var-file=variables/prod.pkrvars.hcl \
-only="*.prod" \
.
- name: Upload artifacts
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: packer-artifacts-${{ github.run_number }}
path: output/
retention-days: 30

The first job fails if formatting or validation fails: it is packer fmt -check -diff that returns code 3 when a file is badly formatted. The second runs only on main, passes the build number and the commit through PKR_VAR_ environment variables, then archives the artifacts for 30 days.

GitLab CI

The GitLab CI equivalent uses the official hashicorp/packer image, pinned by digest. The entrypoint of this image is /bin/packer: without replacing it, GitLab cannot run the script commands, hence entrypoint: [""]. The docker builder needs a Docker daemon, provided by the docker:dind service, with the connection without TLS on port 2375. This service requires a GitLab runner in privileged mode: on a runner that is not, the Docker daemon does not start.

.gitlab-ci.yml
stages:
- validate
- build
variables:
DOCKER_HOST: tcp://docker:2375
DOCKER_TLS_CERTDIR: ""
default:
image:
name: hashicorp/packer:1.16.2@sha256:5aa2160b623fad0b99f8ae8d9cc162ba9775ae428367edca88addc01bb86dd52
entrypoint: [""]
services:
- docker:29.10.0-dind@sha256:4bbc7223f81db790097c6dea42fb93e05b8fead4f0431fbe6ccaba6e8473201c
.packer-init: &packer-init
before_script:
- apk add --no-cache docker-cli
- docker version
- packer version
- packer init .
validate:
stage: validate
<<: *packer-init
script:
- packer fmt -check -diff .
- packer validate .
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
build:dev:
stage: build
<<: *packer-init
script:
- mkdir -p output
- |
packer build \
-var "build_number=$CI_PIPELINE_ID" \
-var "git_commit=$CI_COMMIT_SHA" \
-var "environment=dev" \
-only="*.dev" \
.
rules:
- if: $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH
build:prod:
stage: build
<<: *packer-init
script:
- mkdir -p output
- |
packer build \
-var-file=variables/prod.pkrvars.hcl \
-var "build_number=$CI_PIPELINE_ID" \
-var "git_commit=$CI_COMMIT_SHA" \
-var "environment=prod" \
-only="*.prod" \
.
artifacts:
paths:
- output/
expire_in: 30 days
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

The validate job gives the same verdict as in GitHub Actions. The official hashicorp/packer image, built on Alpine, does not contain the Docker client that the docker builder needs: the before_script installs it with apk add --no-cache docker-cli, then docker version immediately checks that it reaches the Docker-in-Docker service. This pipeline was not run in GitLab: read its output carefully on the first launch.

Makefile for local development

A Makefile gives the same commands locally and in CI. Recipe lines start with a tab, not spaces: with spaces, make answers missing separator.

Makefile
.PHONY: help init fmt validate build clean
help: ## Affiche cette aide
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | \
awk 'BEGIN {FS = ":.*?## "}; {printf " %-15s %s\n", $$1, $$2}'
init: ## Initialise Packer
packer init .
@mkdir -p output
fmt: ## Formate les fichiers HCL
packer fmt -recursive .
validate: init ## Valide les templates
packer validate .
build: validate ## Build toutes les images
packer build .
build-dev: validate ## Build l'image de développement
packer build -only="*.dev" .
build-prod: validate ## Build l'image de production
packer build -var-file=variables/prod.pkrvars.hcl -only="*.prod" .
debug: init ## Build en mode debug
PACKER_LOG=1 packer build -debug -only="*.dev" .
clean: ## Supprime les artefacts
rm -rf output/* manifest*.json *.checksum packer_cache/

With GNU Make 4.4.1, make help lists the nine targets, make validate runs packer init . then packer validate ., and make build-dev builds the development source.

$ make help
help Affiche cette aide
init Initialise Packer
fmt Formate les fichiers HCL
validate Valide les templates
build Build toutes les images
build-dev Build l'image de développement
build-prod Build l'image de production
debug Build en mode debug
clean Supprime les artefacts

CI/CD build variables

Passing the build number and the commit lets you find, in the image or the manifest, the code that produced it.

CI/CD variables
packer build \
-var "build_number=${BUILD_NUMBER}" \
-var "git_commit=${GIT_COMMIT}" \
.

Every variable passed with -var must be declared. A date passed without a declaration (-var "build_date=...") is rejected:

Error: Undefined -var variable
A "build_date" variable was passed in the command line but was not found in
known variables. To declare variable "build_date", place this block in one of
your .pkr files, such as variables.pkr.hcl

Parallel builds

A single template can build several images in one run: one per environment, per provider or per variant. The project of the lesson already does it, with three sources in the build block. Packer builds these images in parallel, except with -debug, which runs them one after the other. To serialize builds without debug mode, add -parallel-builds=1.

Multi-source configuration

The sources attribute of the build block lists the sources to build. only reserves a provisioner for some of them, and except excludes others. The build.pkr.hcl file above is this model: a common provisioner, one for docker.dev, one for docker.prod.

Selection at run time

The -only and -except options of packer build filter the builds at launch. The names have the form build-name.type.source, and the patterns accept the * character.

Filter the builds
# Only the prod source
packer build -only="*.prod" .
# Full name, with that of the build block
packer build -only="app-build.docker.prod" .
# Only staging
packer build -only="*.staging" .

The first command produces output/mywebapp-prod-1.0.0.tar, the third builds only the staging source. Combining -except and -only calls for care: when -except matches none of the builds retained by -only, Packer reports it with a warning, without failing. The sample output below comes from such a combination (-except="*.dev" with -only="*.staging").

Warning: an 'except' option was passed, but did not match any build.
Possible build names: [app-build.docker.dev app-build.docker.staging
app-build.docker.prod].
These could also be matched with a glob pattern like: 'happycloud.*'

Build optimization

Builds are slow when each one redownloads the same packages and starts from the same raw image. Two techniques reduce this cost: a nearby package mirror, and a base image that already contains the common packages.

Package cache

Pointing the package manager at a nearby mirror avoids crossing the Internet on every build. The address below is a placeholder: replace it with that of your mirror. As is, it makes the build fail, with a DNS resolution error (DNS: no address for host).

build.pkr.hcl (excerpt)
provisioner "shell" {
inline = [
"echo 'http://mirrors.example.com/alpine/v3.24/main' > /etc/apk/repositories",
"apk update && apk add --no-cache curl wget"
]
}

Custom base images

For frequent builds, a base image built once, with the common packages, avoids reinstalling them. The first build creates the image, and a docker-tag post-processor gives it a name that the second build finds. The source of the second build carries pull = false: without it, Docker looks for local/base on a remote registry and fails. The tag is versioned (3.24-1), never latest.

This example is played in a separate folder from the project of the lesson: it reuses the project's packer.pkr.hcl and common.pkr.hcl files, and its second build is called app-build, a name already taken by the project's build.

base.pkr.hcl
source "docker" "base" {
image = var.base_image
commit = true
}
build {
name = "base-image"
sources = ["source.docker.base"]
provisioner "shell" {
inline = [
"apk update",
"apk add --no-cache curl wget ca-certificates"
]
}
post-processor "docker-tag" {
repository = "local/base"
tags = ["3.24-1"]
}
}
source "docker" "app" {
image = "local/base:3.24-1"
commit = true
pull = false
}

The second build, in a separate file, starts from this image and checks that curl is present:

app.pkr.hcl
build {
name = "app-build"
sources = ["source.docker.app"]
provisioner "shell" {
inline = ["apk info curl"]
}
}

As long as the base image does not exist, packer build -only="app-build.*" . fails:

==> app-build.docker.app: Error determining source Docker image Id: Error: exit status 1
[...]
==> app-build.docker.app: Stderr: error: no such object: local/base:3.24-1
[...]
==> app-build.docker.app: Error running container: Docker exited with a non-zero exit status.
==> app-build.docker.app: Stderr: Unable to find image 'local/base:3.24-1' locally
==> app-build.docker.app: docker: Error response from daemon: pull access denied for local/base, repository does not exist or may require 'docker login'

With the docker-tag, the first build announces the created label:

==> base-image.docker.base (docker-tag): Repository: local/base:3.24-1

You build the base image first with packer build -only="base-image.*" ., then the application image with packer build -only="app-build.*" .. This second build succeeds: apk info curl prints the package description there.

A tag like 3.24-1 is not frozen: if you rebuild the base, Packer moves the tag to the new image, without a message: two builds of the base give two different image identifiers (Image ID) under the same local/base:3.24-1 tag. So change the number (3.24-2) at every rebuild of the base, in the docker-tag and in the source that consumes it.

CI/CD troubleshooting

When a build works locally and fails in CI, compare the three usual points: the Packer version, the environment variables and the access to the network and to Docker. Pin the Packer version in CI, print packer version at the start of the pipeline, and compare the variables with env | grep PKR.

Timeout while downloading plugins

A cache of the plugins folder avoids redownloading them on every job. The cache key depends on the content of the .pkr.hcl files: it changes when a plugin constraint changes.

GitHub Actions with cache
- name: Cache Packer plugins
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ~/.config/packer/plugins
key: packer-plugins-${{ hashFiles('**/*.pkr.hcl') }}
- name: Initialize Packer
run: packer init .

Docker permission errors

The permission denied while trying to connect to the Docker daemon error means that the job cannot talk to the Docker daemon. In CI, provide a daemon: a runner that has access to one, or the docker:dind service of the GitLab CI example above.

Key takeaways

A Packer project is organized into files by responsibility: packer.pkr.hcl for the versions, one sources file per builder, one variables file with description and validation, locals for derived values, and the build block apart. The *.auto.pkrvars.hcl files are loaded only if they are at the root of the project; those in a subfolder are passed with -var-file.

A ~> constraint with three numbers is narrow: ~> 1.15.0 rejects Packer 1.16.2. Choose ~> 1.16 for Packer and ~> 1.1 for a plugin, and pin images by digest. A variable passed with -var must be declared, otherwise Packer answers Undefined -var variable.

For secrets, declare the variable with sensitive = true, pass it through PKR_VAR_, and keep secret files out of Git: the masking protects the logs, not the content of the image. To debug, PACKER_LOG=1 traces Packer, -debug puts builds in step-by-step mode, and -on-error=abort leaves the machine to inspect, before you delete it by hand. -on-error=run-cleanup-provisioner plays the template's cleanup and retries nothing.

A local base image needs a docker-tag post-processor and pull = false in the source that uses it. CI replays packer fmt -check, packer init, packer validate, then packer build on the main branch, with actions pinned on their SHA.

Knowledge check

These questions cover what the lesson has just explained: the project structure, the version constraints, secrets, debugging and CI.

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