A Packer template in HCL2 is a folder of .pkr.hcl files that describes three
things: the plugins it needs (the packer block), the starting point of
the image (the source block) and what you do to it (the build block).
This lesson is for anyone who has installed Packer and wants to write a first
clean template. You will write a project split across several files, check it
with packer fmt, packer validate and packer inspect, and learn to read
the real error messages.
What you will learn
- Explain why you write a template in HCL2 rather than JSON.
- Tell the
packer,sourceandbuildblocks apart, and what each one declares. - Organize a template across several files in the same folder.
- Check a template with
packer fmt,packer validateandpacker inspect. - Build an image on two systems with a single definition.
- Fix the most frequent validation errors from their message.
Prerequisites
- Packer installed, as in the lesson Install Packer.
- The notions from the lesson Concepts and architecture: builder, provisioner, post-processor.
- Docker up and running, as in the lesson
Install Docker Engine 29 and prove it works
of the Docker course, a prerequisite of this course. The commands assume a
user who runs
dockerwithoutsudo.
The notions of block, label and argument in HCL are recalled as the lesson goes on. To go further, the lesson HCL syntax (in French) details the syntax, and HCL block schema explains why each tool only accepts its own blocks.
Why write a Packer template in HCL2 rather than JSON?
HCL2 is the current format of Packer templates: it accepts comments, reformats
itself automatically and is read folder by folder. The old JSON templates (a
*.json file with builders and provisioners) still exist and still
validate, but they remain a legacy format.
The table compares what changes day to day. The "Target file" and "Reformatting" rows come from tested commands, the other two describe the formats.
| Aspect | Legacy JSON template | HCL2 template |
|---|---|---|
| Comments | Not provided by the JSON format | # and // |
| Target file | A file passed to the command | A folder, with ., or a single .pkr.hcl file |
| Reformatting | None | packer fmt |
| Source reuse | Copy and paste | A source block cited by several build blocks |
The difference in target file shows up right away. With a legacy.json
template, validation succeeds if you pass the file, and fails if you pass the
folder:
$ packer validate legacy.jsonThe configuration is valid.
$ packer validate .Error: Could not find any config file in .
A config file must be suffixed with `.pkr.hcl` or `.pkr.json`. A folder can bereferenced.In the second case, Packer looks for *.pkr.hcl or *.pkr.json in the folder
and finds nothing: a legacy.json file does not have the right suffix. You
therefore have to either pass it explicitly or convert it. Conversely, an HCL2
template is passed by its folder (packer validate .) or by a single .pkr.hcl
file (packer validate legacy.json.pkr.hcl): both succeed. The reason why each
tool only reads its own suffixes is explained in
HCL block schema.
How do I convert an old JSON template?
packer hcl2_upgrade still exists in Packer 1.16.2: it turns a JSON template
into an HCL2 configuration.
packer hcl2_upgrade legacy.jsonSuccessfully created legacy.json.pkr.hcl. Exit 0The generated file passes packer validate legacy.json.pkr.hcl. It still keeps
traces of the conversion to fix by hand: the source is called autogenerated_1,
the plugin is declared with version = "~> 1", and the image keeps the
reference of the original JSON (here alpine:3.24), without a digest if the
JSON had none. Rename the source, align the plugin constraint with the one of
the project (~> 1.1) and pin the image before committing. The
-with-annotations option, described by packer hcl2_upgrade -help, adds help
comments to the generated file.
What does an HCL2 template look like?
An HCL2 template is made of blocks. A block has a type, labels between
quotes, then a body between braces that holds arguments (name = value):
source "docker" "alpine" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true}Here source is the type, "docker" the builder type, "alpine" the name you
chose, and image and commit are two arguments. Values are strings, numbers,
booleans, lists (["a", "b"]) or maps ({ cle = "valeur" }). The general
syntax is detailed in the lesson
HCL syntax (in
French).
Packer only reads files whose name ends in .pkr.hcl (HCL2) or .pkr.json
(JSON in the HCL2 format). The variables and functions of these files are the
subject of the lesson
Packer variables and functions.
What are the three blocks of a Packer template?
A template is built around three blocks: packer declares the requirements
(Packer version, plugins), source describes the starting point of the image,
and build says which sources to build and with which steps.
The following diagram links the blocks of this lesson's template. Follow the
arrows from left to right: the packer block declares the plugin that
packer init installs, this plugin provides the docker builder to the two
source blocks, and the build block (in color) cites both sources. It then
runs each source in parallel with the same provisioners, each one produces an
image, and the manifest post-processor records the images in a file.
The packer block: which version and which plugins?
The packer block sets the minimum Packer version and lists the plugins to
install. A builder such as docker is not included in Packer: it is a plugin,
downloaded by packer init from this block.
packer { required_version = ">= 1.12.0"
required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } }}required_version uses the usual HashiCorp version constraints (=, !=,
>, >=, <, <= and ~>, according to the Packer documentation). Each
plugin in required_plugins has a version (a constraint) and a source (its
address in the format github.com/<organization>/<plugin>).
The ~> 1.1 constraint accepts every 1.x version from 1.1 onward and refuses a
future 2.x, whose changes could break the template. A >= 1.1.0 constraint
would accept that 2.x without warning. No lock file freezes the version
installed by packer init: the constraint is therefore the only protection.
This protection matters, because packer init downloads a binary from GitHub
and then runs it with your privileges.
After writing this block, run packer init on the folder:
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"This message confirms that the ~> 1.1 constraint was resolved to version
1.1.5. The installation folder depends on the user: here root, hence
/root/.config/packer/plugins. packer plugins installed lists the plugins
that are present.
The two errors of this block are easy to trigger. First, a version constraint that no Packer version satisfies:
Error: Unsupported Packer Core version
on plugins.pkr.hcl line 2, in packer: 2: required_version = ">= 99.0.0"
This configuration does not support Packer version 1.16.2. To proceed, eitherchoose another supported Packer version or update this version constraint.Version constraints are normally set for good reason, so updating the constraintmay lead to other errors or unexpected behavior.And a plugin that is declared but not yet installed, when packer init has not
been run:
Error: Missing plugins
The following plugins are required, but not installed:
* github.com/hashicorp/docker ~> 1.1
Did you run packer init for this project ?In both cases, the message names the cause: read it before looking elsewhere.
The source block: which image do you start from?
A source block configures a builder: the way to produce an image on a
given platform. Its format is source "TYPE" "NAME", where TYPE is the
builder (docker, qemu, amazon-ebs...) and NAME an identifier of your
choice. The pair of type and name must be unique in the template.
For a Docker image, image gives the starting image and commit = true asks
Packer to save the resulting image at the end of the build. Two sources let you
build on two systems:
source "docker" "alpine" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true
changes = [ "LABEL project=demo", "LABEL environment=development" ]}
source "docker" "debian" { image = "debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2" commit = true
changes = [ "LABEL project=demo", "LABEL environment=development" ]}changes adds Dockerfile instructions to the final image, here two labels. A
source block builds nothing on its own: a build block has to cite it.
A source declared twice under the same type and the same name is refused:
Error: Duplicate source block
on sources.pkr.hcl line 21: (source code not available)
This source block has the same builder type and name as a previous blockdeclared at sources.pkr.hcl:1,1-25. Each source must have a unique name perbuilder type.The build block: what do you do to the image?
The build block cites the sources to build in sources, then declares
provisioners (the steps that configure the image) and post-processors
(the treatments applied to the resulting artifact). A source is cited in the
form source.TYPE.NAME.
build { name = "mon-build"
sources = [ "source.docker.alpine", "source.docker.debian" ]
provisioner "shell" { inline = [ "echo 'Construction de ${source.name}'", "echo 'Type de builder : ${source.type}'" ] }
post-processor "manifest" { output = "manifest.json" }}Provisioners run in the order they are written, which matters when a step
depends on the previous one (install a package, then test it). In a
provisioner, ${source.name} and ${source.type} give the name and the type
of the source being built. Provisioners are detailed in the lesson
Packer provisioners, post-processors in
Packer post-processors.
The name field of the build appears in the messages: with
name = "mon-build", Packer prefixes the lines with mon-build.docker.alpine;
without name, it only shows docker.alpine.
How do I split a template across several files?
Packer reads all the .pkr.hcl files of a folder as a single template. You can
therefore store each family of blocks in its own file, and a build block can
cite a source defined in another file.
Répertoiremon-projet-packer/
- plugins.pkr.hcl
- sources.pkr.hcl
- builds.pkr.hcl
The plugins.pkr.hcl file holds the packer block, sources.pkr.hcl the two
source blocks, and builds.pkr.hcl the build block, as written above. You
then pass the folder, not a file, to the commands:
packer init .packer validate .packer build .The packer validate . command answers, when everything is in order:
The configuration is valid.This organization separates what rarely changes (the plugins), what describes the targets (the sources) and what describes the actions (the builds). It also keeps a single file from growing endlessly. Variables can have their own file too, as explained in Packer variables and functions.
How do I check a template before building it?
Three commands check a template without building anything: packer fmt fixes
the formatting, packer validate checks consistency, and packer inspect
shows the structure. The first two deserve a place in your CI.
packer fmt: format the files
packer fmt rewrites HCL2 files in the canonical format: two-space indentation
and aligned = signs. Here is a deliberately badly formatted file (a
counter-example to avoid, whose image is not pinned to keep the diff
readable):
source "docker" "alpine" {image = "alpine:3.20" commit = true changes = ["LABEL a=b"]}
build { sources = ["source.docker.alpine"] provisioner "shell" { inline = ["echo hi"] }}With -check, packer fmt reports the files to fix without modifying them,
and returns code 3. Combined with -diff, it shows the changes it would make:
packer fmt -check -diff .bad.pkr.hcl--- old/bad.pkr.hcl+++ new/bad.pkr.hcl@@ -1,12 +1,12 @@ source "docker" "alpine" {-image = "alpine:3.20"- commit = true+ image = "alpine:3.20"+ commit = true changes = ["LABEL a=b"] }
build {- sources = ["source.docker.alpine"]+ sources = ["source.docker.alpine"] provisioner "shell" {- inline = ["echo hi"]+ inline = ["echo hi"] } }The first line gives the name of the affected file, then the diff shows the
removed (-) and added (+) lines. The file has not been modified: that is
what packer fmt . does, as does packer fmt -diff ., which prints the same
diff and rewrites the file. After either command, packer fmt -check . prints
nothing and exits with code 0.
The exit code 3 of -check is what makes a CI pipeline fail: a
packer fmt -check . step rejects a badly formatted change.
packer validate: check the template
packer validate loads all the files, checks that each block is recognized and
that the references exist, without creating an image. Run it before every
packer build.
A build block that cites an undeclared source is refused, and the message
lists the known sources:
Error: Unknown source docker.fedora
on builds.pkr.hcl line 1: (source code not available)
Known: [docker.alpine docker.debian]When the plugin is neither declared nor installed, Packer does not know where
the docker builder comes from and says so. This test was run in a
single-file project, main.pkr.hcl, on a machine with no plugin installed:
Error: Unknown source type docker
on main.pkr.hcl line 6: (source code not available)
The source docker is unknown by Packer, and is likely part of a plugin that isnot installed.You may find the needed plugin along with installation instructions documentedon the Packer integrations page.
https://developer.hashicorp.com/packer/integrations?filter=dockerThe message appears only once, with the only source of this project. The fix is
to add the packer block with required_plugins, then run packer init ..
The message says "not installed", not "not declared": if the plugin is already
installed on the machine, removing the required_plugins block does not make
packer validate . fail. The block is still indispensable: on a fresh machine
or in a CI, nothing is installed, and it is what tells packer init what to
download.
packer inspect: show the structure
packer inspect lists the variables, locals and builds of a template, with
their sources, provisioners and post-processors. It is a quick way to check
that a folder contains what you think it does.
packer inspect .Packer Inspect: HCL2 mode
> input-variables:
> local-variables:
> builds:
> mon-build:
sources:
docker.alpine
docker.debian
provisioners:
shell
post-processors:
0: manifestThe first two sections are empty, because the template has no variable and no
local. Under builds, the name mon-build comes from the name field of the
build block, and the two sources are the ones it cites.
Full example: build an Alpine image with curl
This example brings the three blocks together in a folder of two files,
installs curl in an Alpine image and records the result in a manifest.json
file.
-
Create the folder and the plugins file.
Terminal window mkdir packer-demo && cd packer-demoIn this folder, write the
plugins.pkr.hclfile with thepackerblock given above, withversion = "~> 1.1". -
Write
main.pkr.hcl.source "docker" "alpine" {image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf"commit = true}build {sources = ["source.docker.alpine"]provisioner "shell" {inline = ["apk add --no-cache curl","curl --version"]}post-processor "manifest" {output = "manifest.json"}} -
Install the plugin, then validate.
Terminal window packer init .packer validate .Validation must answer
The configuration is valid. -
Run the build.
Terminal window packer build . -
Read the manifest.
Terminal window cat manifest.json
The build pulls the image by its digest, starts a container, runs the
provisioner, then saves the image. Here are the lines to look for in the
output, from the start of the build to the end (removed lines are replaced by
[...]):
docker.alpine: output will be in this color.
==> docker.alpine: Creating a temporary directory for sharing data...==> docker.alpine: Pulling Docker image: alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf[...]==> docker.alpine: Starting docker container...[...]==> docker.alpine: Provisioning with shell script: /tmp/packer-shell1159434016==> docker.alpine: (1/9) Installing brotli-libs (1.2.1-r0)[...]==> docker.alpine: (9/9) Installing curl (8.23.0-r0)==> docker.alpine: Executing busybox-1.37.0-r31.trigger==> docker.alpine: OK: 13.1 MiB in 25 packages==> 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: Committing the container==> docker.alpine: Image ID: sha256:b4e5e384535321ab44cf86cdf0458aef45183d9d034ddad7b9d7cb9944d5fb58==> docker.alpine: Killing the container: ea7a568a4fba3deb028fda46926ed6349590a850ceb837fa58d0d1adc1d0c9e6==> docker.alpine: Running post-processor: (type manifest)Build 'docker.alpine' finished after 2 seconds 944 milliseconds.
==> Wait completed after 2 seconds 944 milliseconds
==> Builds finished. The artifacts of successful builds are:--> docker.alpine: Imported Docker image: sha256:b4e5e384535321ab44cf86cdf0458aef45183d9d034ddad7b9d7cb9944d5fb58--> docker.alpine: Imported Docker image: sha256:b4e5e384535321ab44cf86cdf0458aef45183d9d034ddad7b9d7cb9944d5fb58The curl 8.23.0 ... line is the output of curl --version in the container:
it proves that the package is installed in the image. The
sha256:b4e5e384... identifier is the one of the image that was created; yours
will be different.
The --> line appears twice, with the same identifier. Without the manifest
post-processor, it appears only once: manifest adds its own artifact line. It
does not produce a second image. The manifest.json file records this result:
{ "builds": [ { "name": "alpine", "builder_type": "docker", "build_time": 1795075326, "files": null, "artifact_id": "sha256:b4e5e384535321ab44cf86cdf0458aef45183d9d034ddad7b9d7cb9944d5fb58", "packer_run_uuid": "32d862aa-68f5-834a-eeff-9ca56bd2a1ee", "custom_data": null } ], "last_run_uuid": "32d862aa-68f5-834a-eeff-9ca56bd2a1ee"}The artifact_id field repeats the identifier of the image, and name the
name of the source. Another tool in your chain can read this file to know which
image has just been produced.
How do I build two systems with a single build?
When a build block cites two sources, Packer builds both in parallel, and
each provisioner runs on each of them. With the three-file project from the
section "How do I split a template across several files?", packer build .
gives this (main lines, the others are replaced by [...]):
mon-build.docker.alpine: output will be in this color.mon-build.docker.debian: output will be in this color.[...]==> mon-build.docker.alpine: Construction de alpine==> mon-build.docker.alpine: Type de builder : docker==> mon-build.docker.debian: Construction de debian==> mon-build.docker.debian: Type de builder : docker[...]Build 'mon-build.docker.alpine' finished after 2 seconds 128 milliseconds.[...]Build 'mon-build.docker.debian' finished after 2 seconds 238 milliseconds.
==> Wait completed after 2 seconds 238 milliseconds
==> Builds finished. The artifacts of successful builds are:--> mon-build.docker.alpine: Imported Docker image: sha256:0bbe796bba874e5ef5ce68649808399726343a388ae1cca851a95401fd0898a6--> mon-build.docker.alpine: Imported Docker image: sha256:0bbe796bba874e5ef5ce68649808399726343a388ae1cca851a95401fd0898a6--> mon-build.docker.debian: Imported Docker image: sha256:822306e7995b5eeca69f273f001650742c6867d7fa1194465a0b4563ab825c9a--> mon-build.docker.debian: Imported Docker image: sha256:822306e7995b5eeca69f273f001650742c6867d7fa1194465a0b4563ab825c9aThe Construction de alpine and Construction de debian lines show that
${source.name} takes the value of the source being built. The manifest
contains two entries, one per source, and each artifact appears twice in the
final list, because manifest adds its own line.
The trap appears when a provisioner assumes a specific system. Alpine installs
its packages with apk, which Debian does not know. To see it, replace the
content of builds.pkr.hcl in the three-file project with this build, without
a name, where both sources share an apk add provisioner. It fails on Debian
(debian:trixie-slim):
build { sources = ["source.docker.alpine", "source.docker.debian"]
provisioner "shell" { inline = [ "echo 'Construction de ${source.name}'", "apk add --no-cache curl" ] }}[...]==> docker.debian: Construction de debian==> docker.debian: /tmp/script_6808.sh: 3: apk: not found==> docker.debian: Provisioning step had errors: Running the cleanup provisioner, if present...==> docker.debian: Killing the container: 10f9373310522f326c16c242736f017643b5f945a93b5dcf3905f3395b8af774==> docker.alpine: Construction de alpineBuild 'docker.debian' errored after 1 second 713 milliseconds: Script exited with non-zero exit status: 127. Allowed exit codes are: [0][...]Build 'docker.alpine' finished after 2 seconds 992 milliseconds.
==> Wait completed after 2 seconds 992 milliseconds
==> Some builds didn't complete successfully and had errors:--> docker.debian: Script exited with non-zero exit status: 127. Allowed exit codes are: [0]
==> Builds finished. The artifacts of successful builds are:--> docker.alpine: Imported Docker image: sha256:23605308a411075f9f9c3660a6e0141ff24dc73843790ff506dadde47b1d7d4cShell code 127 means "command not found". Note that the Alpine source still
finishes and produces its image: a failing source does not stop the others,
but the packer build command exits with code 1.
The fix is to reserve each provisioner for its own source with only, which
lists the sources concerned, and to give Debian its own package manager,
apt-get:
build { sources = ["source.docker.alpine", "source.docker.debian"]
provisioner "shell" { only = ["docker.alpine"] inline = [ "apk add --no-cache curl", "curl --version | head -1" ] }
provisioner "shell" { only = ["docker.debian"] inline = [ "apt-get update -qq", "apt-get install -y -qq curl", "curl --version | head -1" ] }}With this template, both sources end with Imported Docker image and the
command exits with code 0. On Debian, curl installs in version 8.14.1; on
Alpine, in 8.23.0. The debconf messages that appear during the installation
on Debian (unable to initialize frontend: Dialog) are harmless: debconf
finds neither a TERM variable nor a terminal for the provisioner script, and
falls back to its Noninteractive mode.
only takes the form TYPE.NAME, for example docker.alpine, without the
source. prefix you write in sources. This is the form that packer inspect
displays. The trap is silent: in a named build (name = "mon-build"),
only = ["source.docker.alpine"] or only = ["mon-build.docker.alpine"]
passes packer validate . with The configuration is valid., and both builds
end with code 0, but the provisioner runs on no source at all. Only the
docker.alpine form makes it run, on Alpine only. To check that a provisioner
did run, look in the output for a line it prints itself (an echo, for
example), prefixed by the expected source.
Troubleshooting
The messages below are the ones Packer 1.16.2 returned during the tests. Each row gives the exact start of the message, what it means and the fix.
| Message | Cause | Fix |
|---|---|---|
Unknown source docker.fedora followed by Known: [docker.alpine docker.debian] | A build cites a source that does not exist | Fix the source.TYPE.NAME reference from the Known list |
Duplicate source block | Two source blocks with the same type and name | Rename one of the two sources |
Unsupported Packer Core version | required_version is not satisfied by the installed Packer version | Update Packer or relax the constraint |
Missing plugins with Did you run packer init for this project ? | A plugin of required_plugins is not installed | Run packer init . |
Unknown source type docker | The builder plugin is neither declared nor installed | Add the plugin to required_plugins, then packer init . |
Could not find any config file in . | The folder contains no .pkr.hcl or .pkr.json file | Name the files with the right suffix (see HCL block schema), or pass a legacy JSON template by its file name |
apk: not found with code 127 | A provisioner uses a command that the source's system does not have | Reserve the apk provisioner for Alpine with only = ["docker.alpine"], and give Debian an apt-get provisioner with only = ["docker.debian"] |
packer validate succeeds, but a provisioner ran on no source | An only written as source.docker.alpine or mon-build.docker.alpine designates no source | Write only = ["docker.alpine"] |
packer fmt -check . exits with code 3 | At least one file is not in the canonical format | Run packer fmt . and commit the result |
If the message is not in this table, read it again in full: Packer states the file, the line and, often, the expected fix.
Key takeaways
A Packer template in HCL2 is a folder of .pkr.hcl files that Packer reads as
a single whole. The packer block declares the Packer version and the plugins,
the source block describes the starting point of the image, and the build
block cites the sources to build with their provisioners and post-processors.
The packer init . command installs the declared plugins: on a machine where
the plugin is not yet installed, validation fails with Missing plugins. The
packer validate . command checks the template before the build, and its
messages name the source, the file and the line at fault.
For formatting, packer fmt -check . reports badly formatted files through
exit code 3 without modifying them, and packer fmt . fixes them. When a build
cites several sources, a failing source does not stop the others, and only
reserves a provisioner for the source that supports it, with the form
docker.alpine and not source.docker.alpine. An old JSON template is
converted with packer hcl2_upgrade, then reworked by hand: source name,
plugin constraint aligned on ~> 1.1, pinned image.
Knowledge check
These questions cover what the lesson has just explained: the three blocks, the checking commands and their messages.
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 variables, locals and functions
A new full quiz with random questions
Work again only on the questions you missed