A post-processor is a step of the build block that transforms the
artifact once the image is built: writing a traceability file (manifest),
computing a checksum (checksum), creating an archive (compress), or
importing, tagging and pushing a Docker image. This lesson is for anyone who
already knows how to build an image with Packer and wants to automate what
comes after. You will write each post-processor, chain them, and read the
errors they return.
What you will learn
- Generate a JSON manifest with the build metadata.
- Create checksum files and verify them.
- Compress an artifact into
tar.gz,ziporlz4. - Chain post-processors, and tell a chain from independent blocks.
- Import, tag and push a Docker image to a registry.
- 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 provisioners of the lesson Packer provisioners.
- A working Docker, as in the lesson
Install Docker Engine 29 and prove it works,
usable without
sudo.
What is a post-processor?
A post-processor is a post-processor block placed in the build block. It
receives the artifact that the builder has just produced (a file, a Docker
image) and transforms it. Post-processors run after all the provisioners.
Their writing order is not enough to fix what each one receives. A
post-processors block (plural) forms a chain: each step receives the
artifact of the previous one. post-processor blocks (singular) placed side
by side are independent: each one receives the original artifact of the
builder. The section on chaining shows the difference with an example.
| Post-processor | Use | Output |
|---|---|---|
manifest | Build traceability | JSON metadata file |
checksum | Integrity check | Checksum files |
compress | Archiving | .tar.gz, .zip, .lz4 |
docker-import | Import a tarball as an image | Local Docker image |
docker-tag | Add tags to an image | Image with tags |
docker-push | Push to a registry | Published image |
Which starter project for the examples?
The examples share two files, to create once. The first declares the Docker
plugin. The second defines two sources: example keeps the image in Docker
(commit = true), and app exports it to an app.tar file (export_path).
This choice matters: some post-processors work on an image, others on a file,
and the troubleshooting section comes back to this difference.
packer { required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } }}source "docker" "example" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" commit = true}
source "docker" "app" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" export_path = "app.tar"}Each example goes in a build.pkr.hcl file in the same folder. Run
packer init . once, then packer validate . and packer build . for each
example. Delete the produced files between two examples.
The manifest post-processor
The manifest post-processor writes a JSON file that describes the
build: source name, builder type, date, produced files and artifact
identifier. A CI pipeline uses it to find the image it has just built.
Basic configuration
The manifest only needs the path of the output file. The following template
installs curl in the image, then writes manifest.json.
build { sources = ["source.docker.example"]
provisioner "shell" { inline = ["apk add --no-cache curl"] }
post-processor "manifest" { output = "manifest.json" }}The produced file contains one entry per build. Look at artifact_id, the
identifier of the Docker image, and packer_run_uuid, identical for all the
builds of a same run. The files and custom_data fields are null when
the build produces no file and you give no data.
{ "builds": [ { "name": "example", "builder_type": "docker", "build_time": 1795082095, "files": null, "artifact_id": "sha256:1607e458c14f47a1092f8008ed5f11448fbda825082730c64115936fbdddf56f", "packer_run_uuid": "b4e31f62-e39b-ae57-8393-7562fa75ec27", "custom_data": null } ], "last_run_uuid": "b4e31f62-e39b-ae57-8393-7562fa75ec27"}The build_time field is a Unix timestamp, in seconds.
Custom metadata
The custom_data option adds your own keys to the manifest: version, commit,
environment. They tie an image to the version of the code that produced it.
The variables must be declared, for example in a variables.pkr.hcl file.
variable "app_version" { default = "1.0.0"}
variable "environment" { default = "dev"}
variable "git_commit" { default = "abc123"}build { sources = ["source.docker.example"]
post-processor "manifest" { output = "manifest.json" strip_path = true
custom_data = { version = var.app_version environment = var.environment build_date = timestamp() git_commit = var.git_commit author = "DevOps Team" } }}The manifest then contains the custom_data keys, sorted alphabetically:
"custom_data": { "author": "DevOps Team", "build_date": "2026-11-19T09:55:04Z", "environment": "dev", "git_commit": "abc123", "version": "1.0.0" }The table describes the options of the manifest post-processor.
| Option | Type | Description |
|---|---|---|
output | string | Path of the JSON output file |
strip_path | bool | Keep only the file names in the files list |
custom_data | map | Custom metadata, key and value |
The manifest appends each build to the existing file instead of replacing
it. After two successive packer build ., the file contains two entries;
after packer build -force ., it contains only one. For a pipeline that
always reads the last entry, jq '.builds[-1]' is enough, but deleting the
file before the build avoids mix-ups.
Use in CI/CD
A pipeline reads the manifest with jq to retrieve the image identifier and
the version, then passes them to the next step (scan, deployment). The jq
tool must be installed on the machine that runs the pipeline.
# Extract the last artifact_idARTIFACT_ID=$(jq -r '.builds[-1].artifact_id' manifest.json)echo "Image créée : $ARTIFACT_ID"
# Extract the custom versionVERSION=$(jq -r '.builds[-1].custom_data.version' manifest.json)echo "Version : $VERSION"With the manifest of the previous example, the script prints the image identifier, then the version:
$ sh ci.shImage créée : sha256:40822bb3b4421d91e69d7988394cdc4849ecb320000e22fd003cef240477671fVersion : 1.0.0The checksum post-processor
The checksum post-processor writes checksum files that let you verify
that an artifact was not altered after a transfer or a download. It accepts
md5, sha1, sha224, sha256, sha384 and sha512. It works on a file:
use the app source, which exports app.tar.
Basic configuration
The template asks for two algorithms and a name pattern for the output files. The variables between double braces are explained in the next section.
build { sources = ["source.docker.app"]
provisioner "shell" { inline = ["apk add --no-cache htop vim"] }
post-processor "checksum" { checksum_types = ["sha256", "md5"] output = "{{.BuildName}}_{{.ChecksumType}}.checksum" }}This template produces two files, app_sha256.checksum and
app_md5.checksum, next to app.tar. Each file contains the sum and the
file name separated by a tab. The table describes the options.
| Option | Type | Description |
|---|---|---|
checksum_types | list | Algorithms to compute |
output | string | Name pattern of the output files |
Template variables
The output pattern accepts variables between double braces to name a file
by algorithm and by source. Without {{.ChecksumType}} in the name and with
several algorithms, the files would overwrite each other.
| Variable | Value |
|---|---|
{{.BuildName}} | Name of the source (app here) |
{{.BuilderType}} | Builder type (docker here) |
{{.ChecksumType}} | Algorithm (sha256 for example) |
With checksum_types = ["sha1", "sha512"] and the pattern
{{.BuildName}}_{{.BuilderType}}_{{.ChecksumType}}.sum, Packer announces the
created files:
--> docker.app: Created artifact from files: app.tar, app_docker_sha1.sum, app_docker_sha512.sumIntegrity check
The check is done with the sha256sum -c command (or md5sum -c) on the sum
file, in the folder where the artifact is. The expected result is
app.tar: OK.
The result depends on the tool. The file written by Packer separates the sum
and the file name with a tab. The GNU sha256sum (coreutils) accepts it
and answers app.tar: OK. The busybox 1.37.0 one, installed by default on
Alpine 3.24, rejects it: the check then fails although the artifact has not
changed.
$ sha256sum -c app_sha256.checksumsha256sum: WARNING: 1 of 1 computed checksums did NOT matchBefore concluding that the artifact was altered, replace the tab with two spaces, then rerun the check:
$ sed 's/\t/ /' app_sha256.checksum > fixed.checksum$ sha256sum -c fixed.checksumapp.tar: OKYou can also use the GNU sha256sum, or compare by hand the sum in the file
with the one that sha256sum app.tar computes. The md5 file has the same
flaw with busybox's md5sum.
Prefer sha256 or stronger to distribute an artifact: md5 and sha1 do
not protect against deliberate tampering and are only good for detecting a
transfer error.
The compress post-processor
The compress post-processor creates an archive of the artifact. The
format is inferred from the extension of the output file.
Basic configuration
The following template archives app.tar as .tar.gz. The {{timestamp}}
variable in the output name gives a Unix timestamp, in seconds.
build { sources = ["source.docker.app"]
provisioner "shell" { inline = ["apk add --no-cache nginx"] }
post-processor "compress" { output = "{{.BuildName}}-{{timestamp}}.tar.gz" compression_level = 6 keep_input_artifact = true }}The output announces the pgzip algorithm and the number of cores used, then
the archive name. The name contains the timestamp, in the form
app-1795082111.tar.gz.
The table describes the options of the compress post-processor. With
keep_input_artifact = false (default value), the original file is deleted
after compression; with true, it stays next to the archive.
| Option | Type | Description |
|---|---|---|
output | string | Archive path, the format comes from the extension |
compression_level | int | Compression level, from 1 (fast) to 9 (maximum) |
keep_input_artifact | bool | Keep the original artifact after compression |
Supported formats
The format depends on the extension of output. The table gives the format
obtained for six extensions, which you recognize by the first bytes of the
file.
| Extension | Resulting format |
|---|---|
.tar.gz and .tgz | gzip (bytes 1f 8b) |
.zip | ZIP (bytes 50 4b) |
.tar | tar, no compression |
.lz4 and .tar.lz4 | LZ4 (bytes 04 22 4d 18) |
Chaining post-processors
A post-processors block makes its steps a chain: each step receives the
artifact of the previous one. This is what lets you compute the checksum of
the archive rather than that of the original file.
post-processors block or post-processor block?
The two syntaxes do not produce the same result. The following skeleton puts
them side by side, with braces to fill in ({ ... }): it illustrates the
structure and is not a template to run as is.
build { sources = ["source.docker.app"]
# post-processors block (plural): a chain. # Each step receives the artifact of the previous one. post-processors { post-processor "compress" { ... } post-processor "checksum" { ... } post-processor "manifest" { ... } }
# post-processor block (singular): independent of the chain. # It receives the original artifact of the builder. post-processor "manifest" { ... }}The diagram follows the artifact in both cases. On the right, in a chain,
compress receives the original artifact, then checksum and manifest
each receive the result of the previous step. On the left, separate blocks
all receive the original artifact: none sees the work of the others.
To see it, take compress (with output = "c.tar.gz") and checksum (with
output = "c.sha256") in two separate post-processor blocks. Both run, but
the checksum computed is that of app.tar (the original file), and not that
of the c.tar.gz archive. The sha256sum command on both files gives two
different sums:
$ sha256sum app.tar c.tar.gz2838a80ed111c752e4e2977804234ffce28882880adc30b2ee05bb6f25bcdcf0 app.tar27b530e302dcc7a00f958767f0337a99bf3004e2ea5cee4935c4af6e76091933 c.tar.gzThe c.sha256 file contains the sum starting with 2838a80e: it is that of
app.tar.
Full chaining example
The following workflow chains compression, the archive checksum, then the
final manifest. The three steps are in a single post-processors block.
variable "version" { type = string default = "1.0.0"}
variable "environment" { type = string default = "dev"}
build { sources = ["source.docker.app"]
provisioner "shell" { inline = [ "echo 'Installing application stack...'", "apk add --no-cache python3 py3-pip nginx" ] }
post-processors { post-processor "compress" { output = "app-${var.version}.tar.gz" compression_level = 9 keep_input_artifact = false }
post-processor "checksum" { checksum_types = ["sha256"] output = "app-${var.version}.sha256" }
post-processor "manifest" { output = "app-${var.version}-manifest.json" strip_path = true
custom_data = { version = var.version environment = var.environment build_date = timestamp() } } }}At the end of the build, the folder contains the archive, its checksum and
the manifest, but no longer app.tar, deleted after compression. The
checksum covers the archive: the sum in the app-1.0.0.sha256 file is the
one that sha256sum app-1.0.0.tar.gz computes.
app-1.0.0-manifest.jsonapp-1.0.0.sha256app-1.0.0.tar.gzDuring the build, Packer announces the compression with pgzip, then the
checksum, then the manifest:
==> docker.app (compress): Using pgzip compression with 16 cores for app-1.0.0.tar.gz[...]==> docker.app: Running post-processor: (type checksum)==> docker.app: Running post-processor: (type manifest)The manifest of a chain lists the two produced files in files, and its
artifact_id is empty, since no image is produced:
"files": [ { "name": "app-1.0.0.tar.gz", "size": 24369981 }, { "name": "app-1.0.0.sha256", "size": 82 } ], "artifact_id": "",Several chains in one build
A build can contain several post-processors blocks. Each chain receives the
original artifact of the builder and does not see the work of the others.
They are written one after the other in the file, and the build output
displays them one after the other.
build { sources = ["source.docker.app"]
# Chain 1: tar.gz archive and its checksum post-processors { post-processor "compress" { output = "app.tar.gz" } post-processor "checksum" { checksum_types = ["sha256"] output = "app.tar.gz.sha256" } }
# Chain 2: zip archive and its checksum post-processors { post-processor "compress" { output = "app.zip" } post-processor "checksum" { checksum_types = ["sha256"] output = "app.zip.sha256" } }}The build produces two archives and two checksums: app.tar.gz,
app.tar.gz.sha256, app.zip and app.zip.sha256.
Docker post-processors
The Docker post-processors plug Packer into a container workflow: import a
tarball as an image, tag it, push it to a registry. They come from the
docker plugin, already declared in plugins.pkr.hcl, and are installed with
packer init .. The packer plugins install github.com/hashicorp/docker
command installs the same plugin without going through a template, but it
sets no version constraint.
docker-import
The docker-import post-processor imports a tarball (produced by
export_path) as an image in the local Docker daemon. The changes option
adds metadata to it, with the syntax of Dockerfile instructions.
variable "image_name" { type = string default = "myapp"}
variable "image_version" { type = string default = "1.0.0"}
build { sources = ["source.docker.app"]
provisioner "shell" { inline = [ "echo 'Building ${var.image_name}:${var.image_version}'", "apk add --no-cache curl jq" ] }
post-processor "docker-import" { repository = "local/${var.image_name}" tag = var.image_version
changes = [ "ENV APP_VERSION=${var.image_version}", "LABEL maintainer=devops@example.com", "LABEL version=${var.image_version}", "WORKDIR /app", "EXPOSE 8080" ] }}The build announces the repository and the tag of the imported image. Then
check that the metadata is really in the image with docker image inspect:
the environment variable, the labels, the working folder and the exposed port
are there.
==> docker.app (docker-import): Repository: local/myapp:1.0.0$ docker image inspect local/myapp:1.0.0 --format '{{json .Config.Env}} | {{json .Config.Labels}} | wd={{.Config.WorkingDir}} | {{json .Config.ExposedPorts}}'["APP_VERSION=1.0.0"] | {"maintainer":"devops@example.com","version":"1.0.0"} | wd=/app | {"8080/tcp":{}}The table describes the main options.
| Option | Type | Description |
|---|---|---|
repository | string | Repository name (local/myapp for example) |
tag | string | Image tag |
changes | list | Dockerfile instructions to apply |
keep_input_artifact | bool | Keep the tarball after the import |
platform | string | Target platform, for multi-architecture |
Supported changes instructions
The changes option accepts Dockerfile instructions. With Packer 1.16.2, the
eight instructions of the table apply; the right-hand column says what the
image configuration (docker image inspect) shows for each one.
| Instruction | Example | Effect seen in the image |
|---|---|---|
CMD | CMD ["nginx", "-g", "daemon off;"] | Cmd set |
ENTRYPOINT | ENTRYPOINT /start.sh | Entrypoint as /bin/sh -c /start.sh |
ENV | ENV APP_ENV production | Env contains APP_ENV=production |
EXPOSE | EXPOSE 80 443 | Ports 80/tcp and 443/tcp exposed |
LABEL | LABEL version=1.0 | version label |
USER | USER appuser | User equal to appuser |
WORKDIR | WORKDIR /app | WorkingDir equal to /app |
VOLUME | VOLUME /data /logs | /data and /logs volumes |
For ENV, both forms are accepted: ENV APP_VERSION=1.0.0 gives
Env=["APP_VERSION=1.0.0"], and ENV APP_ENV production, without an equals
sign, gives APP_ENV=production.
docker-tag
The docker-tag post-processor adds tags to an image already present in
Docker. Placed after docker-import in a chain, it tags the imported image.
Repeating in tags the tag given to docker-import is pointless for tagging
the image, which already carries it. It becomes useful before a
docker-push: in a chain that contains a docker-tag, docker-push pushes
only the tags of the image produced by that docker-tag.
post-processors { post-processor "docker-import" { repository = "local/${var.image_name}" tag = var.image_version }
post-processor "docker-tag" { repository = "local/${var.image_name}" tags = ["latest", "${var.image_version}-alpine"] }}The image then carries three tags: 1.0.0 (given by docker-import),
latest and 1.0.0-alpine. The table describes the options.
| Option | Type | Description |
|---|---|---|
repository | string | Repository name |
tags | list | Tags to add |
force | bool | Force even if the tag exists |
The docker-tag post-processor only accepts artifacts of the Docker builder
that stay in Docker. On the example source (commit = true), it works
without docker-import. On the app source (export_path), it fails:
* Post-processor failed: Unknown artifact type: packer.dockerCan only tag from Docker builder artifacts.docker-push
The docker-push post-processor pushes the image to a Docker registry.
To try it without an account, a local registry is enough (the lesson Serve a
trusted registry, and log in to it
details its installation with TLS). The following examples use the official
registry:3.1.2 image (version 3 of the distribution registry), protected
by htpasswd authentication, on port 5001.
The password is never typed in the command: it would end up in the shell
history and in the process list, visible to every user of the machine. It is
read from a file whose access you control. Here, the ~/.secrets/regpass
file contains a randomly drawn password, and htpasswd reads it on its
standard input with -i. A > redirection creates, by default, a file that
every account on the machine can read (permissions 0644). The umask 077,
run in a subshell between parentheses so as not to change your session,
creates the file as 0600: only you can read it.
mkdir -p -m 700 ~/.secrets( umask 077; head -c 12 /dev/urandom | od -An -tx1 | tr -d ' \n' > ~/.secrets/regpass )mkdir authhtpasswd -B -i -n alice < ~/.secrets/regpass > auth/htpasswddocker run -d --name reg -p 5001:5000 -v "$PWD/auth:/auth" \ -e REGISTRY_AUTH=htpasswd \ -e REGISTRY_AUTH_HTPASSWD_REALM=registry \ -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd \ registry:3.1.2@sha256:82f6ff4a7f982960c8aa51617fea3aabc485df6e55cce80d22deb1de36f1bc3cThe htpasswd command comes from the apache2-utils package (Debian) or
httpd-tools (Red Hat). The template imports the image, adds the 1.0.0 and
latest tags, then pushes it. The credentials come from variables, never
from the file.
variable "registry_username" { type = string}
variable "registry_password" { type = string sensitive = true}
variable "image_version" { type = string default = "1.0.0"}
build { sources = ["source.docker.app"]
post-processors { post-processor "docker-import" { repository = "localhost:5001/myapp" tag = var.image_version }
post-processor "docker-tag" { repository = "localhost:5001/myapp" tags = [var.image_version, "latest"] }
post-processor "docker-push" { login = true login_server = "localhost:5001" login_username = var.registry_username login_password = var.registry_password } }}The credentials go through PKR_VAR_... environment variables, read by
Packer as template variables. Here, the user name is written in clear text
and the password is read from the file created above:
export PKR_VAR_registry_username=aliceexport PKR_VAR_registry_password="$(cat ~/.secrets/regpass)"packer build .The form packer build -var registry_password=secret . is to be avoided: the
value would stay in the shell history and in the process list.
To check the result, query the registry with the same credentials. The
curl -u alice:secret command would pose the same problem. Put the
credential in a configuration file read by curl -K instead:
( umask 077; { printf 'user = "alice:'; cat ~/.secrets/regpass; echo '"'; } > ~/.secrets/curlrc )curl -s -K ~/.secrets/curlrc localhost:5001/v2/myapp/tags/listThe build imports the image, tags it twice, then pushes it. The useful lines of the output show the two pushed tags, with the same digest:
==> docker.app: Running post-processor: (type docker-tag)==> docker.app (docker-tag): Tagging image: localhost:5001/myapp:1.0.0==> docker.app (docker-tag): Repository: localhost:5001/myapp:1.0.0==> docker.app (docker-tag): Tagging image: localhost:5001/myapp:1.0.0==> docker.app (docker-tag): Repository: localhost:5001/myapp:latest==> docker.app: Running post-processor: (type docker-push)[...]==> docker.app (docker-push): Pushing: localhost:5001/myapp:latest[...]==> docker.app (docker-push): latest: digest: sha256:899d02458d92baa3cb81b7abd1de35298279721c65c7388b6aa63dc005cbe66f size: 405==> docker.app (docker-push): Pushing: localhost:5001/myapp:1.0.0[...]==> docker.app (docker-push): 1.0.0: digest: sha256:899d02458d92baa3cb81b7abd1de35298279721c65c7388b6aa63dc005cbe66f size: 405[...]The rest of the output pushes latest a second time: the layer is already in
the registry (Layer already exists), and this second upload changes
nothing.
The registry lists the two tags:
{"name":"myapp","tags":["1.0.0","latest"]}docker-push pushes only the tags of the final artifact of the chain,
here the image produced by docker-tag. If tags listed only latest, the
1.0.0 tag created by docker-import would stay in Docker, on your machine,
and the registry would contain only latest. So always push both.
The version tag (1.0.0) is the one you deploy: it designates a precise
image. latest is only a mutable alias: the next push will move it to
another image, and a deployment that refers to it no longer knows which
version it runs.
Two errors are recognized by their message. With a wrong password, the login is refused:
==> docker.app (docker-push): Logging in...==> docker.app (docker-push): Error response from daemon: login attempt to http://localhost:5001/v2/ failed with status: 401 Unauthorized[...]* Post-processor failed: Error logging in to Docker: Bad exit status: 1With login = false on a registry that requires authentication, the push
goes out without credentials and the registry refuses it. The build then
fails too, with the same closing message as for a wrong password, without the
mention of the login:
==> docker.app (docker-push): push access denied, repository does not exist or may require authorization: authorization failed: no basic auth credentials[...]* Post-processor failed: Bad exit status: 1When the DOCKER_CONFIG environment variable is not set, Packer pushes with
a temporary Docker configuration folder, which contains no session: a
docker login already open on your machine therefore does not make the push
pass, and the build fails the same way.
The push reuses a session only if DOCKER_CONFIG points to the folder that
contains it, for example export DOCKER_CONFIG=$HOME/.docker. In that case,
the Creating temporary Docker configuration directory line no longer
appears in the output.
The table describes the main options of docker-push.
| Option | Type | Description |
|---|---|---|
login | bool | Log in before the push |
login_server | string | Registry address |
login_username | string | User name |
login_password | string | Password or token |
ecr_login | bool | AWS ECR authentication |
keep_input_artifact | bool | Keep the local image after the push |
Full Docker workflow
Here is the same sequence toward ghcr.io, with a manifest placed outside
the chain, which records the registry, the version and the tags in
custom_data. This template passes packer validate when its variables are
declared. The push to ghcr.io was not tested: try it first on the local
registry above.
variable "version" { default = "1.0.0"}
variable "github_username" { type = string}
variable "github_token" { type = string sensitive = true}
build { sources = ["source.docker.app"]
provisioner "shell" { inline = ["apk add --no-cache ca-certificates curl"] }
post-processors { post-processor "docker-import" { repository = "ghcr.io/myorg/myapp" tag = var.version
changes = [ "ENV APP_VERSION=${var.version}", "LABEL org.opencontainers.image.version=${var.version}", "EXPOSE 8080" ] }
post-processor "docker-tag" { repository = "ghcr.io/myorg/myapp" tags = [var.version, "latest"] }
post-processor "docker-push" { login = true login_server = "ghcr.io" login_username = var.github_username login_password = var.github_token } }
post-processor "manifest" { output = "docker-manifest.json"
custom_data = { registry = "ghcr.io/myorg/myapp" version = var.version tags = "${var.version},latest" } }}The manifest is outside the chain: it receives the original artifact of the
builder (the app.tar tarball), not the pushed image. Both tags, the version
and latest, go to the registry, as in the previous example: the tags
field of the manifest cites both.
Without the variable declarations, validation fails on every attribute that
cites a missing variable, with Unsupported attribute; This object does not have an attribute named "version".
Full production example
This example combines two sources, a provisioner reserved for production and
a compression and checksum chain, with a consolidated manifest outside the
chain. Put it in a separate folder: it declares its own packer block and
its own sources, which would duplicate the files of the starter project.
packer { required_version = "~> 1.16"
required_plugins { docker = { version = "~> 1.1" source = "github.com/hashicorp/docker" } }}
variable "app_name" { type = string description = "Nom de l'application" default = "mywebapp"}
variable "app_version" { type = string description = "Version de l'application" default = "2.0.0"}
variable "build_number" { type = string description = "Numéro de build CI/CD" default = "local"}
locals { full_version = "${var.app_version}-${var.build_number}" artifact_name = "${var.app_name}-${local.full_version}" output_dir = "output"}
source "docker" "dev" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" export_path = "${local.output_dir}/${var.app_name}-dev.tar"}
source "docker" "prod" { image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf" export_path = "${local.output_dir}/${var.app_name}-prod.tar"}
build { name = "complete-build"
sources = [ "source.docker.dev", "source.docker.prod" ]
provisioner "shell" { inline = [ "echo '=== Building ${var.app_name} v${local.full_version} ==='", "apk add --no-cache curl wget" ] }
provisioner "shell" { only = ["docker.prod"] inline = [ "echo 'Adding production tools...'", "apk add --no-cache nginx" ] }
post-processors { post-processor "compress" { output = "${local.output_dir}/${local.artifact_name}-${source.name}.tar.gz" compression_level = 9 keep_input_artifact = false }
post-processor "checksum" { checksum_types = ["sha256"] output = "${local.output_dir}/${local.artifact_name}-${source.name}.sha256" } }
post-processor "manifest" { output = "${local.output_dir}/manifest-${local.artifact_name}.json" strip_path = true
custom_data = { app_name = var.app_name app_version = var.app_version full_version = local.full_version build_number = var.build_number build_date = timestamp() } }}The output folder must exist before the build. The build number comes from a
variable of your CI; without it, it is local.
mkdir -p outputpacker build -var "app_version=2.1.0" -var "build_number=${CI_BUILD_NUMBER:-local}" \ 06-exemple-complet.pkr.hclWith CI_BUILD_NUMBER=42, the output/ folder contains seven files, not
five. The two archives and their checksums are expected. The two original
tarballs, mywebapp-dev.tar and mywebapp-prod.tar, stay, because the
post-processor "manifest" (singular, outside the chain) receives the
original artifact: keep_input_artifact = false deletes nothing as long as
another block still holds the file.
Répertoireoutput/
- manifest-mywebapp-2.1.0-42.json
- mywebapp-2.1.0-42-dev.sha256
- mywebapp-2.1.0-42-dev.tar.gz
- mywebapp-2.1.0-42-prod.sha256
- mywebapp-2.1.0-42-prod.tar.gz
- mywebapp-dev.tar
- mywebapp-prod.tar
The consolidated manifest contains two entries, dev and prod, whose
artifact_id is Container, and whose files lists the original tarball.
If you want to find the archives in the manifest, put the
post-processor "manifest" at the end of the chain, as in the chaining
example.
Troubleshooting
The table gathers the errors met in this lesson.
| Symptom | Cause | Solution |
|---|---|---|
Unknown artifact type: packer.docker with docker-tag | The source exports a file (export_path), not an image | Use a commit = true source, or place docker-tag after docker-import |
| Archive checksum different from the expected one | compress and checksum are in separate post-processor blocks | Group them in a post-processors block |
login attempt to ... failed with status: 401 Unauthorized | Wrong registry credentials | Test docker login by hand, check the variable |
push access denied ... no basic auth credentials | Push without login | login = true with login_username and login_password |
Unsupported attribute; This object does not have an attribute named ... | Variable cited but not declared | Add the variable block |
manifest.json missing after the build | A provisioner failed before the post-processor | Fix the provisioner: no manifest is written on a failed build |
sha256sum -c says did NOT match on Alpine | busybox's sha256sum reads the sum file differently from GNU | Check with the GNU sha256sum, or compare the sums by hand |
For a build that fails without a clear message, rerun with
PACKER_LOG=1 packer build . and read the output starting from the last
Running post-processor line.
Key takeaways
A post-processor transforms the artifact after the build. A post-processors
block forms a chain in which each step receives the artifact of the previous
one, whereas separate post-processor blocks all receive the original
artifact: this is what explains a checksum that does not match the archive.
The manifest writes one JSON per build, with custom_data for your own
keys, and appends builds to the file instead of replacing it. The checksum
writes one sum per algorithm, which is verified with the GNU sha256sum and
not always with the busybox one. The compress infers the format from the
extension.
On the Docker side, docker-import creates an image from a tarball,
docker-tag only accepts images that stay in Docker, and docker-push
requires login = true with credentials coming from sensitive variables. In
the full example, keep_input_artifact = false does not delete a file that
the manifest of the build still holds.
Knowledge check
These questions cover chaining, the three file post-processors and the Docker post-processors.
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 best practices
A new full quiz with random questions
Work again only on the questions you missed