A provisioner is a step of the build block that configures the image after
the machine created by the builder has started: installing packages, copying
files, running scripts or an Ansible playbook. This lesson is for anyone who
can write a Packer template and now wants to put something in it. You will use
the shell, file, shell-local and ansible provisioners, tune their
common options, and learn to read the errors they return.
What you will learn
- Run shell commands and scripts on the image being built.
- Transfer files and directories to the image, and bring some back.
- Run commands on your machine to prepare or clean up the build.
- Configure the image with an Ansible playbook.
- Pause a build with
breakpoint, and set pauses, retries, per-source filters and cleanup after a failure. - Read the most frequent errors and fix them.
Prerequisites
- Packer installed, as in the lesson Install Packer.
- A template split across several files, as in the lesson HCL2 templates.
- The variables and functions of the lesson Variables and functions.
- A working Docker, as in the lesson
Install Docker Engine 29 and prove it works,
usable without
sudo. All the examples build images with thedockerbuilder. - Ansible installed on your machine, because the
ansibleprovisioner runs there, as in the lesson Install Ansible (in French).
What is a provisioner?
A provisioner is a provisioner block placed in the build block. The
builder creates the machine (a container here, a virtual machine elsewhere);
the provisioner configures it; Packer then saves the result as an image.
Provisioners run in the order they are written, and that matters: a file
must be transferred before it is used, and Python must be installed before an
Ansible playbook.
The table summarizes the five provisioners of the lesson and where each one works.
| Provisioner | Where it acts | Main use |
|---|---|---|
shell | On the image being built | Scripts, package installation |
file | Between your machine and the image | Configuration, scripts, data |
shell-local | On the machine that runs Packer | Preparation, generation, cleanup |
ansible | On your machine, from which Ansible connects to the image | Complex configuration |
breakpoint | Pauses the build | Interactive debugging |
Which starter project for the examples?
The examples of this lesson contain only the build block. They share two
files that you create once: plugins.pkr.hcl, which declares the Docker
plugin, and sources.pkr.hcl, which defines two sources, alpine and
debian. Without these two files, source.docker.alpine does not exist and
packer validate fails.
packer { required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } }}source "docker" "alpine" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true}
source "docker" "debian" { image = "debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2" commit = true}Each example goes in a build.pkr.hcl file in the same folder, which you
replace from one example to the next. You run it with three commands,
packer init . once, then packer validate . and packer build .. The
alpine and debian images come from the lesson on
HCL2 templates:
Alpine for its light weight, Debian when an example needs bash or apt.
The shell provisioner
The shell provisioner runs commands or scripts on the image being
built. With the docker builder, Packer sends the script into the
container and runs it with docker exec; with a virtual machine, it goes
through SSH. It is the equivalent of logging in to the machine and typing the
commands.
Inline commands
The inline option is the simplest method for a few commands. Packer writes
them to a temporary script, sends it to the image and runs it: the commands
therefore share the same shell.
build { sources = ["source.docker.alpine"]
provisioner "shell" { inline = [ "echo '=== Début du provisioning ==='", "apk update", "apk add --no-cache curl jq vim", "echo '=== Vérification des installations ==='", "curl --version | head -1", "jq --version", "echo '=== Provisioning terminé ==='" ] }}In the build output, every line the script prints is prefixed with
==> docker.alpine:. Look for the three === markers and the curl and jq
versions: they prove that the commands ran in the image and not on your
machine.
$ packer build .docker.alpine: output will be in this color.
==> docker.alpine: Creating a temporary directory for sharing data...[...]==> docker.alpine: Provisioning with shell script: /tmp/packer-shell144668659==> docker.alpine: === Début du provisioning ===[...]==> docker.alpine: === Vérification des installations =====> docker.alpine: curl 8.23.0 (x86_64-alpine-linux-musl) libcurl/8.23.0 OpenSSL/3.5.9 zlib/1.3.2 brotli/1.2.1 zstd/1.5.7 c-ares/1.34.9 libidn2/2.3.8 libpsl/0.21.5 nghttp2/1.70.0==> docker.alpine: jq-1.8.2==> docker.alpine: === Provisioning terminé =====> docker.alpine: Committing the container[...]--> docker.alpine: Imported Docker image: sha256:9536c5c3fcec0997fec01d3bbfd1e9dd18a620fc31844d524801a8a9a85d2d11The table describes the main options of the shell provisioner.
| Option | Type | Description |
|---|---|---|
inline | list of strings | Commands to run (incompatible with script) |
script | string | Path of a script to send and run |
scripts | list of strings | Several scripts, run in order |
environment_vars | list of strings | Environment variables in KEY=value format |
inline_shebang | string | Interpreter of the inline commands (default: /bin/sh -e) |
execute_command | string | Custom execution command |
valid_exit_codes | list of integers | Accepted exit codes (default: [0]) |
External scripts
As soon as a script grows past a few lines, put it in a file: it reads
better, can be reused and can be tested outside Packer. The following
template calls one script with script, then two others with scripts. The
scripts must exist before packer validate, otherwise validation fails.
variable "environment" { type = string default = "development" description = "Environnement cible (development, staging, production)"}
build { sources = ["source.docker.alpine"]
provisioner "shell" { script = "scripts/setup.sh"
environment_vars = [ "ENVIRONMENT=${var.environment}", "BUILD_DATE=${timestamp()}" ] }
provisioner "shell" { scripts = [ "scripts/install-tools.sh", "scripts/cleanup.sh" ] }}The first script reads the environment variables passed by
environment_vars:
#!/bin/sh# Initial configuration script
set -e # Stop on error
echo "=== Configuration de l'environnement ==="echo "Environnement: ${ENVIRONMENT:-non défini}"echo "Date du build: ${BUILD_DATE:-non défini}"
# Package updateapk update
# Environment-specific configurationcase "${ENVIRONMENT}" in production) echo ">>> Configuration production..." ;; staging) echo ">>> Configuration staging..." ;; development) echo ">>> Configuration développement..." ;;esac
echo "=== Configuration terminée ==="The two other scripts are reduced here to one line each, so that the example
runs without any other file. Create them in scripts/:
echo "install-tools ok"echo "cleanup ok"If you run packer validate . before creating them, Packer names each
missing file:
$ packer validate .Error: Failed preparing provisioner-block "shell" ""
on build.pkr.hcl line 25: (source code not available)
2 error(s) occurred:
* Bad script 'scripts/install-tools.sh': stat scripts/install-tools.sh: no suchfile or directory* Bad script 'scripts/cleanup.sh': stat scripts/cleanup.sh: no such file ordirectoryOnce the scripts are in place, the build chains the three scripts in order.
The command packer build -var environment=production . changes the value of
the variable: the script then prints >>> Configuration production....
$ packer build .[...]==> docker.alpine: Provisioning with shell script: scripts/setup.sh==> docker.alpine: === Configuration de l'environnement =====> docker.alpine: Environnement: development==> docker.alpine: Date du build: 2026-11-19T09:54:39Z[...]==> docker.alpine: >>> Configuration développement...==> docker.alpine: === Configuration terminée =====> docker.alpine: Provisioning with shell script: scripts/install-tools.sh==> docker.alpine: install-tools ok==> docker.alpine: Provisioning with shell script: scripts/cleanup.sh==> docker.alpine: cleanup okPacker environment variables
Packer injects a few environment variables into the scripts. They let you write a single script that adapts to the builder or to the source.
| Variable | Value |
|---|---|
PACKER_BUILD_NAME | Name of the source being built (alpine here), not the name of the build block |
PACKER_BUILDER_TYPE | Builder type (docker here) |
PACKER_HTTP_ADDR | Address of Packer's HTTP server, only if an HTTP server is configured |
A script that runs env | grep -E '^PACKER' | sort in an alpine source
prints the first two:
==> docker.alpine: PACKER_BUILDER_TYPE=docker==> docker.alpine: PACKER_BUILD_NAME=alpineThe HCL expression ${build.name} is a different mechanism: it holds the
name field of the build block. On a build without name, it is empty: a
script that receives it in a BN variable through environment_vars prints
BN=.
Exit codes and errors
A script that ends with a code other than 0 makes the provisioner fail, and
the build stops. This behavior protects you: an ignored error would produce
an incomplete image. With inline, the message looks like this:
Build 'docker.alpine' errored after 1 second 405 milliseconds: Script exited with non-zero exit status: 1. Allowed exit codes are: [0]For a command that can legitimately fail, such as grep, which returns 1
when it finds nothing, declare the accepted code with valid_exit_codes:
provisioner "shell" { inline = ["grep nomatchxyz /etc/passwd"] valid_exit_codes = [0, 1]}Without valid_exit_codes, the same command stops the build. An
alternative is to write grep pattern file || true in the command, but it
also hides the real grep errors.
Two traps come from the interpreter in use:
- The
-eof the default shebang (/bin/sh -e) applies only toinline. A file given toscriptdoes not stop at the first failure: with a script that containsfalsethenecho apres-false-script, the build succeeds and printsapres-false-script. Putset -eat the top of your scripts. bash-specific syntax, such as[[ ]], fails under/bin/sh. On Debian, the build stops with[[: not foundand code 127.
==> docker.debian: /tmp/script_7649.sh: 2: [[: not found[...]Build 'docker.debian' errored after 4 seconds 570 milliseconds: Script exited with non-zero exit status: 127. Allowed exit codes are: [0]The fix is to change the interpreter, keeping -e:
provisioner "shell" { inline_shebang = "/bin/bash -e" inline = ["[[ 1 -eq 1 ]] && echo bashisme-ok"]}Finally, inline and script are mutually exclusive. Writing them together
makes validation fail with Only a script file or an inline script can be specified, not both.
Handling reboots
When provisioning requires a reboot (updated kernel, system configuration),
the connection drops. The expect_disconnect option tells Packer that this
is expected, and pause_before gives the machine time to reboot before the
next step.
provisioner "shell" { expect_disconnect = true inline = [ "apt-get update && apt-get upgrade -y", "reboot" ]}
provisioner "shell" { pause_before = "30s" inline = ["echo 'Machine redémarrée, on continue...'"]}This example is for a virtual machine builder. In a Debian container, the
reboot command does not exist: the build stops with reboot: not found,
and there is nothing to restart.
The file provisioner
The file provisioner transfers files or directories between your machine
and the image. It is used to deploy configuration files, scripts or static
data.
Uploading files
The basic use sends a single file to the image. The source file must exist on
your machine, in a files/ folder here: Packer checks it from
packer validate.
build { sources = ["source.docker.alpine"]
provisioner "file" { source = "files/config.json" destination = "/tmp/config.json" }
provisioner "shell" { inline = [ "mkdir -p /etc/myapp", "mv /tmp/config.json /etc/myapp/config.json", "chmod 644 /etc/myapp/config.json" ] }}The files/config.json file contains {"a":1}. The build ends with an
Imported Docker image: sha256:… line. You check the result by running the
image with that identifier:
$ docker run --rm sha256:66953bc5dac18531646791b283ca1ec6d9f22a9e6dff26c3f32bf3558d716eb7 ls -l /etc/myapp/config.json-rw-r--r-- 1 root root 7 Nov 19 10:29 /etc/myapp/config.jsonThe file provisioner writes as the login user. With a virtual machine and a
non-root user, a direct upload to /etc fails: you upload to /tmp first,
then a shell provisioner moves the file with sudo. In a Docker container,
the user is root and the detour is not mandatory, but it keeps the template
valid for both cases.
Uploading directories
A directory is transferred with the same provisioner. The result depends on
the destination and on the presence of a slash. The table shows three cases
with the docker builder; the "Resulting content" column says where the
files land.
| Source | Destination | Resulting content |
|---|---|---|
files/app | /opt/ | /opt/app/hello.txt and /opt/app/sub/x.txt |
files/app/ | /app/ | /app/hello.txt and /app/sub/x.txt |
files/app | /app/ | /app/hello.txt and /app/sub/x.txt |
Remember this: to get an /opt/app/ folder, the destination is the parent
folder /opt/. When the destination is the target folder itself (/app/),
the content is copied into it and there is no /app/app/. These results are
those of the Docker communicator.
The documentation of the file provisioner describes the general rule: a
trailing slash on the source copies the content directly into the
destination, and its absence creates the source folder inside the
destination. It therefore recommends always ending the source with a slash,
for identical behavior on every platform. The behavior with an SSH
communicator was not tested here: check it on your builder before relying on
it.
Dynamic content
Instead of sending an existing file, the content attribute writes a file
whose text is computed by Packer. It is handy for injecting a version or a
build date.
variable "app_version" { type = string default = "1.0.0"}
build { sources = ["source.docker.alpine"]
provisioner "shell" { inline = ["mkdir -p /app"] }
provisioner "file" { content = jsonencode({ version = var.app_version buildDate = timestamp() builder = "packer" }) destination = "/app/build-info.json" }}The destination folder must exist in the image. Without the
mkdir -p /app provisioner, the build stops with this message:
==> docker.alpine: Upload failed: Failed to upload to '/app/build-info.json' in container: destination "df65ca2d27cecdc54c9f3a099addf3bfd47e39f48e74aecd81fd00cb4a7c33ed:/app" must be a directoryWith the folder created, cat /app/build-info.json in the image returns the
expected JSON:
{"buildDate":"2026-11-19T09:55:32Z","builder":"packer","version":"1.0.0"}Files generated during the build
A file created during the build, for example by a shell-local provisioner,
does not exist yet when packer validate runs. Without a precaution,
validation fails with Bad source '...': stat ...: no such file or directory. The generated = true attribute tells Packer to check the file
only at upload time. A complete example follows in the section on
shell-local.
Downloading files
With direction = "download", the provisioner copies a file from the image
to your machine. It is useful for retrieving an installation log or a
generated file.
provisioner "file" { direction = "download" source = "/var/log/install.log" destination = "./build-logs/install.log"}When the file exists in the image, the output contains the line
Downloading /var/log/install.log => ./build-logs/install.log, and the file
appears in build-logs/. When it does not exist, the build fails:
==> docker.alpine: Download failed: Error downloading file: Error response from daemon: Could not find the file /var/log/install.log in container 849cb17170daaca873381517e66f2e9eb446f791cae5b674224f40efccd2f089The shell-local provisioner
The shell-local provisioner runs commands on your machine, the one that
runs Packer, and not in the image. It prepares files before sending them,
generates a configuration, cleans up after the build or notifies an external
system.
Preparing before the build
The example generates a metadata file on your machine, sends it to the image
with generated = true, then deletes the local temporary folder.
locals { build_id = substr(uuidv4(), 0, 8) build_dir = "/tmp/packer-build-${local.build_id}"}
build { sources = ["source.docker.alpine"]
provisioner "shell-local" { inline = [ "echo '=== Préparation locale ==='", "echo 'Build ID: ${local.build_id}'", "mkdir -p ${local.build_dir}", "echo '{\"build_id\": \"${local.build_id}\"}' > ${local.build_dir}/metadata.json" ] }
provisioner "file" { source = "${local.build_dir}/metadata.json" destination = "/tmp/metadata.json" generated = true }
provisioner "shell-local" { inline = [ "echo '=== Nettoyage local ==='", "rm -rf ${local.build_dir}" ] }}In the output, the prefix of the first and last steps is
Running local shell script, and not Provisioning with shell script: that
is the sign that they run on your machine. The 90252b19 identifier is drawn
at random on every build.
==> docker.alpine: Running local shell script: /tmp/packer-shell1699308837==> docker.alpine: === Préparation locale =====> docker.alpine: Build ID: 90252b19==> docker.alpine: Uploading /tmp/packer-build-90252b19/metadata.json => /tmp/metadata.json==> docker.alpine: Running local shell script: /tmp/packer-shell263844341==> docker.alpine: === Nettoyage local ===The content of /tmp/metadata.json in the image is {"build_id": "90252b19"},
and the /tmp/packer-build-90252b19 folder no longer exists on your machine.
Filtering by OS
The only_on option limits a shell-local provisioner to certain operating
systems, the one that runs Packer. It is meant for templates shared between
Linux, macOS and Windows workstations.
provisioner "shell-local" { only_on = ["linux", "darwin"] inline = ["uname -a", "id"]}
provisioner "shell-local" { only_on = ["windows"] inline = ["echo %USERNAME%"]}On a Linux workstation, the second block is skipped, and Packer writes it in the output:
==> docker.alpine: Skipping shell-local due to runtime OSDifferences with shell
The two provisioners look alike, but they do not act in the same place. The table summarizes what changes for you.
| Aspect | shell | shell-local |
|---|---|---|
| Where it runs | On the image being built | On the Packer machine |
| Accessible files | Those of the image | Those of your machine |
| Environment variables | Passed by environment_vars | Local environment, plus environment_vars |
| Typical use | Image configuration | Preparation and cleanup |
The Ansible provisioner
The ansible provisioner runs an Ansible playbook from your machine
against the image being built. It suits long or repeated configurations, and
it reuses your existing roles. To learn Ansible itself, follow the
Ansible training
(in French); this lesson covers only how to plug it into Packer.
Installing the plugin
The ansible provisioner is not built into Packer: it lives in a plugin to
declare alongside the Docker plugin, in the packer block.
packer { required_version = "~> 1.16"
required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } ansible = { version = "~> 1.1" source = "github.com/hashicorp/ansible" } }}The packer init . command installs both plugins. It prints one line per
installed plugin, with its version:
$ packer init .Installed plugin github.com/hashicorp/docker v1.1.5 in "/root/.config/packer/plugins/github.com/hashicorp/docker/packer-plugin-docker_v1.1.5_x5.0_linux_amd64"Installed plugin github.com/hashicorp/ansible v1.1.6 in "/root/.config/packer/plugins/github.com/hashicorp/ansible/packer-plugin-ansible_v1.1.6_x5.0_linux_amd64"Ansible must also be installed on your machine (the one that runs Packer), and the target image must contain Python. The template below installs Python in the image before calling Ansible.
Basic configuration
This example builds a Debian image. The shell provisioner installs Python,
then Ansible plays the playbook, receiving two variables. The source needs no
particular setting: Ansible connects to the container without run_command.
variable "environment" { type = string default = "development"}
variable "app_version" { type = string default = "1.0.0"}
source "docker" "debian_ansible" { image = "debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2" commit = true}
build { sources = ["source.docker.debian_ansible"]
provisioner "shell" { inline = [ "apt-get update", "apt-get install -y python3 python3-apt", "ln -sf /usr/bin/python3 /usr/bin/python" ] }
provisioner "ansible" { playbook_file = "ansible/playbook.yml"
extra_arguments = [ "--extra-vars", "app_version=${var.app_version} deploy_env=${var.environment}" ]
ansible_env_vars = [ "ANSIBLE_HOST_KEY_CHECKING=False", "ANSIBLE_NOCOLOR=True" ]
groups = ["webservers"] }}The Ansible variable is called deploy_env and not environment, because
environment is a reserved name in Ansible. With that name, Ansible
prints [WARNING]: Found variable using reserved name 'environment' and the
playbook receives an empty value (Environnement: [] in the debug message).
Example playbook
The playbook installs a few packages, creates /app and writes a version
file in it. It reads the app_version and deploy_env variables sent by
Packer.
---- name: Configuration de l'image de base hosts: all become: true
vars: app_version: "1.0.0" deploy_env: "development" packages: - curl - wget - jq - vim - git
tasks: - name: Afficher les informations du build ansible.builtin.debug: msg: "Version: {{ app_version }} - Environnement: {{ deploy_env }}"
- name: Installation des paquets de base ansible.builtin.apt: name: "{{ packages }}" state: present update_cache: true
- name: Création du répertoire application ansible.builtin.file: path: /app state: directory mode: "0755"
- name: Création du fichier de version ansible.builtin.copy: content: | APP_VERSION={{ app_version }} DEPLOY_ENV={{ deploy_env }} dest: /app/version.env mode: "0644"A successful build chains the shell then the playbook, and ends with
Ansible's recap: five ok tasks, three changed, no failed. A failed
count above zero stops the build.
The run_command setting of the docker source is not needed here. It only
replaces the arguments passed to docker run (by default
-d -i -t --entrypoint=/bin/sh -- <image>), for example to give the
container a name. The build succeeds with or without it.
Main options
This table lists the options of the ansible provisioner used above, with
the others you will meet most often. Their default values come from the
plugin documentation and were not tested here.
| Option | Description |
|---|---|
playbook_file | Path of the playbook to run (required) |
extra_arguments | Extra arguments for ansible-playbook |
ansible_env_vars | Environment variables for Ansible |
groups | Inventory groups for the host |
user | Ansible user (ansible_user), by default the one that runs Packer, not the communicator's |
galaxy_file | requirements.yml file for Galaxy roles and collections, empty by default |
use_proxy | Go through a local proxy provided by Packer (true by default) |
Debugging
If Ansible does not do what you expect, ask it for more detail with -v
options; the more there are, the chattier the output.
provisioner "ansible" { playbook_file = "ansible/playbook.yml" extra_arguments = ["-vvvv"]}To see what Packer itself does (connection, commands sent), run the build
with the PACKER_LOG=1 variable. An Ansible build that seems stuck on a
package installation is sometimes waiting for an answer to an interactive
question, like the one from the tzdata package on Ubuntu: look for a prompt
in the output before blaming the network.
Options common to all provisioners
A few options exist on all provisioners: they set the pace of execution, the retries and the time limit.
Timing and retries
The following three options control time and recovery from errors.
provisioner "shell" { pause_before = "10s" timeout = "5m" max_retries = 3
inline = ["echo 'Executed'"]}| Option | Type | Effect |
|---|---|---|
pause_before | duration | Packer writes Pausing 10s before the next provisioner... then waits |
timeout | duration | Past the duration, Cancelling provisioner after a timeout... and the build fails |
max_retries | integer | Number of attempts in addition to the first one |
With max_retries = 2 and a script that always fails, the script runs
three times, the first one and two retries. The message announces the
remaining retries:
==> docker.alpine: Provisioner failed with "Script exited with non-zero exit status: 1. Allowed exit codes are: [0]", retrying with 2 trie(s) left[...]==> docker.alpine: Provisioner failed with "Script exited with non-zero exit status: 1. Allowed exit codes are: [0]", retrying with 1 trie(s) left[...]==> docker.alpine: retry limit reached.With timeout = "5s" on a script that sleeps for 20 seconds, the build stops
after about seven seconds with context canceled.
Filtering by builder
When a build cites several sources, only limits a provisioner to some of
them, and except excludes it from some. The names have the form
docker.alpine, without the source. prefix.
build { sources = ["source.docker.alpine", "source.docker.debian"]
provisioner "shell" { only = ["docker.alpine"] inline = ["echo 'Alpine seulement'"] }
provisioner "shell" { except = ["docker.alpine"] inline = ["echo 'Tout sauf Alpine'"] }
provisioner "shell" { inline = ["echo 'Les deux sources'"] }}In this build, the alpine source plays the first and third provisioners,
and the debian source plays the second and third.
Overriding per builder
The override option changes the options of a provisioner for a specific
source. The key of each entry must be the exact name of the source,
docker.alpine and not alpine. With an inexact name, packer validate
passes, but the override does not apply: the default script runs on both
sources.
build { sources = ["source.docker.alpine", "source.docker.debian"]
provisioner "shell" { inline = ["echo 'Default script'"]
override = { "docker.alpine" = { inline = ["apk add --no-cache curl"] } "docker.debian" = { inline = ["echo debian-override"] } } }}With the exact keys, Alpine installs curl and Debian prints
debian-override. With the alpine and debian keys, both sources print
Default script.
Cleaning up after a failure
When a provisioner fails, Packer destroys the machine and produces no image.
The error-cleanup-provisioner block runs a cleanup step only after a
failure, for example to stop an external service, delete a local temporary
file or notify a team.
build { sources = ["source.docker.alpine"]
provisioner "shell" { inline = ["false"] }
error-cleanup-provisioner "shell-local" { inline = ["echo CLEANUP-LOCAL-EXECUTE"] }}In the output, Packer announces the failure then plays the cleanup. The build stays in error, with exit code 1: the cleanup repairs nothing.
==> docker.alpine: Provisioning step had errors: Running the cleanup provisioner, if present...==> docker.alpine: Running local shell script: /tmp/packer-shell3721326636==> docker.alpine: CLEANUP-LOCAL-EXECUTE[...]Build 'docker.alpine' errored after 1 second 583 milliseconds: Script exited with non-zero exit status: 1. Allowed exit codes are: [0]Execution order and good practices
Provisioners run in the order they appear in the build block. This
sequence lets you build a coherent chain, of which here is a common layout.
Recommended workflow
A well-organized provisioning goes through the following phases. Each phase can have a single provisioner, or none.
-
Local preparation (
shell-local)Generate the configuration files, prepare the working folder.
-
Dependency installation (
shell)Update the system and install the required packages.
-
File upload (
file)Transfer the configurations, scripts and data to the image.
-
Configuration (
shelloransible)Configure the services, create the users, apply the settings.
-
Validation (
shell)Check that the files are there and that the commands answer.
-
Image cleanup (
shell)Delete temporary files and empty the caches.
-
Local cleanup (
shell-local)Delete the temporary files on your machine.
Full example
This example follows the seven phases. It generates config.json locally,
installs the tools, uploads the file, writes a .env file, checks the result
and cleans up. Read it from top to bottom: the order of the provisioner
blocks is the order of execution.
variable "environment" { type = string default = "development"}
variable "app_version" { type = string default = "1.0.0"}
locals { build_id = substr(uuidv4(), 0, 8) full_version = "${var.app_version}-${local.build_id}"
env_config = { development = { debug = true, log_level = "debug" } staging = { debug = false, log_level = "info" } production = { debug = false, log_level = "warn" } }
config = local.env_config[var.environment]}
source "docker" "alpine_demo" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true}
build { name = "complete-demo" sources = ["source.docker.alpine_demo"]
# Phase 1: local preparation provisioner "shell-local" { inline = [ "mkdir -p /tmp/packer-${local.build_id}", "cat > /tmp/packer-${local.build_id}/config.json << 'EOF'", jsonencode({ version = local.full_version environment = var.environment debug = local.config.debug log_level = local.config.log_level }), "EOF" ] }
# Phase 2: package installation provisioner "shell" { inline = [ "apk update", "apk add --no-cache curl jq vim git" ] }
# Phase 3: file upload provisioner "file" { source = "/tmp/packer-${local.build_id}/config.json" destination = "/tmp/config.json" generated = true }
# Phase 4: configuration provisioner "shell" { environment_vars = [ "APP_VERSION=${local.full_version}", "APP_ENV=${var.environment}" ] inline = [ "mkdir -p /app/config", "mv /tmp/config.json /app/config/", "cat > /app/.env << EOF", "APP_VERSION=$APP_VERSION", "APP_ENV=$APP_ENV", "EOF" ] }
# Phase 5: validation provisioner "shell" { inline = [ "echo '=== Validation ==='", "jq . /app/config/config.json", "cat /app/.env", "test -f /app/.env && echo 'OK: .env présent'" ] }
# Phase 6: image cleanup provisioner "shell" { inline = ["rm -rf /tmp/* /var/cache/apk/*"] }
# Phase 7: local cleanup provisioner "shell-local" { inline = ["rm -rf /tmp/packer-${local.build_id}"] }}When the build succeeds, the validation phase prints the JSON formatted by
jq, then the content of /app/.env and OK: .env présent. The prefix of
the lines is complete-demo.docker.alpine_demo, because the build block
carries a name.
The breakpoint provisioner
The breakpoint provisioner pauses the build so that you can inspect the
machine, for example with docker exec, before continuing by pressing Enter.
build { sources = ["source.docker.debian"]
provisioner "shell" { inline = ["apt-get update"] }
provisioner "breakpoint" { note = "Vérifiez que les paquets sont installés avant de continuer" }
provisioner "shell" { inline = ["apt-get install -y nginx"] }}The breakpoint waits for an answer from the keyboard. Run without a
terminal, for example in a CI pipeline, it fails instead of waiting, and
the build stops:
==> docker.debian: Pausing at breakpoint provisioner with note "Vérifiez que les paquets sont installés avant de continuer".==> docker.debian: Provisioning step had errors: Running the cleanup provisioner, if present...[...]Build 'docker.debian' errored after 4 seconds 334 milliseconds: Error asking for input: no available ttyRemove the breakpoint blocks from a template before sending it to CI.
Troubleshooting
The table gathers the errors met in this lesson, with the message that lets you recognize them.
| Symptom | Cause | Solution |
|---|---|---|
Bad script '...': stat ...: no such file or directory | The script or scripts file does not exist | Create the file, or fix the path relative to the launch folder |
Bad source '...': stat ...: no such file or directory | The source of a file does not exist at validation | Fix the path, or generated = true if a provisioner creates it |
[[: not found, code 127 | bash syntax run by /bin/sh | inline_shebang = "/bin/bash -e" |
| Build succeeded although a command of a script failed | The -e does not apply to script | set -e at the top of the script |
Only a script file or an inline script can be specified, not both. | inline and script in the same block | Keep only one of the two |
destination ... must be a directory | The destination folder does not exist in the image | Create the folder with a shell provisioner before the upload |
Error asking for input: no available tty | A breakpoint without a terminal | Remove the breakpoint or run the build in a terminal |
| Override without effect | The key is not the exact name of the source | Write docker.alpine, not alpine |
Found variable using reserved name 'environment' | Ansible variable with a reserved name | Rename the variable, deploy_env for example |
When none of these messages matches, rerun the build with
PACKER_LOG=1 packer build . and read the output starting from the last
Provisioning with shell script or Running local shell script line: the
error is right after it.
Key takeaways
A provisioner configures the machine the builder has just created, and
provisioners run in the order they are written in the build block. An
example can only be replayed if the sources, plugins, scripts and files it
cites exist: without them, validation fails before any build.
The shell provisioner stops the build at the first failure with inline,
thanks to the -e of the /bin/sh -e shebang, but not with script: add
set -e to your scripts. bash syntax requires
inline_shebang = "/bin/bash -e", and valid_exit_codes accepts a
particular exit code, such as 1 for grep.
The file provisioner copies in both directions. For a file, its destination
folder must exist in the image, and generated = true covers files created
during the build. The shell-local provisioner acts on your machine, and
ansible runs a playbook from it: give it variables whose name is not
reserved.
On the common options side, max_retries = 2 gives three runs, override
requires the exact name of the source, and error-cleanup-provisioner only
runs after a failure. A breakpoint fails without a terminal.
Knowledge check
These questions cover the shell, file, shell-local, ansible and
breakpoint provisioners, their common options and the errors they return.
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: Packer post-processors
A new full quiz with random questions
Work again only on the questions you missed