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

By updated

Improve this page

Logo Packer

A 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, zip or lz4.
  • 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

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-processorUseOutput
manifestBuild traceabilityJSON metadata file
checksumIntegrity checkChecksum files
compressArchiving.tar.gz, .zip, .lz4
docker-importImport a tarball as an imageLocal Docker image
docker-tagAdd tags to an imageImage with tags
docker-pushPush to a registryPublished 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.

plugins.pkr.hcl
packer {
required_plugins {
docker = {
version = "~> 1.1"
source = "github.com/hashicorp/docker"
}
}
}
sources.pkr.hcl
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.pkr.hcl
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.

manifest.json
{
"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.

variables.pkr.hcl
variable "app_version" {
default = "1.0.0"
}
variable "environment" {
default = "dev"
}
variable "git_commit" {
default = "abc123"
}
build.pkr.hcl
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.

OptionTypeDescription
outputstringPath of the JSON output file
strip_pathboolKeep only the file names in the files list
custom_datamapCustom 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.

ci.sh
# Extract the last artifact_id
ARTIFACT_ID=$(jq -r '.builds[-1].artifact_id' manifest.json)
echo "Image créée : $ARTIFACT_ID"
# Extract the custom version
VERSION=$(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.sh
Image créée : sha256:40822bb3b4421d91e69d7988394cdc4849ecb320000e22fd003cef240477671f
Version : 1.0.0

The 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.pkr.hcl
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.

OptionTypeDescription
checksum_typeslistAlgorithms to compute
outputstringName 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.

VariableValue
{{.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.sum

Integrity 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.checksum
sha256sum: WARNING: 1 of 1 computed checksums did NOT match

Before 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.checksum
app.tar: OK

You 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.pkr.hcl
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.

OptionTypeDescription
outputstringArchive path, the format comes from the extension
compression_levelintCompression level, from 1 (fast) to 9 (maximum)
keep_input_artifactboolKeep 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.

ExtensionResulting format
.tar.gz and .tgzgzip (bytes 1f 8b)
.zipZIP (bytes 50 4b)
.tartar, no compression
.lz4 and .tar.lz4LZ4 (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.

Structure of the post-processors
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.

Two ways of writing three post-processors. In a post-processors block, which forms a chain, compress receives the original artifact of the builder, checksum receives the archive produced by compress, and manifest receives the result of checksum. In three separate post-processor blocks, compress, checksum and manifest each receive the original artifact of the builder.Separate blocksChainarchivearchiveOriginal artifactfrom the buildercompresschecksummanifestcompresschecksummanifest
Source · SVG
Esc to close, + and − to zoom, scroll to move around. 100 %

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.gz
2838a80ed111c752e4e2977804234ffce28882880adc30b2ee05bb6f25bcdcf0 app.tar
27b530e302dcc7a00f958767f0337a99bf3004e2ea5cee4935c4af6e76091933 c.tar.gz

The 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.

build.pkr.hcl
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.json
app-1.0.0.sha256
app-1.0.0.tar.gz

During 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.pkr.hcl
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.

build.pkr.hcl
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.

OptionTypeDescription
repositorystringRepository name (local/myapp for example)
tagstringImage tag
changeslistDockerfile instructions to apply
keep_input_artifactboolKeep the tarball after the import
platformstringTarget 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.

InstructionExampleEffect seen in the image
CMDCMD ["nginx", "-g", "daemon off;"]Cmd set
ENTRYPOINTENTRYPOINT /start.shEntrypoint as /bin/sh -c /start.sh
ENVENV APP_ENV productionEnv contains APP_ENV=production
EXPOSEEXPOSE 80 443Ports 80/tcp and 443/tcp exposed
LABELLABEL version=1.0version label
USERUSER appuserUser equal to appuser
WORKDIRWORKDIR /appWorkingDir equal to /app
VOLUMEVOLUME /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.

docker-import then docker-tag chain
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.

OptionTypeDescription
repositorystringRepository name
tagslistTags to add
forceboolForce 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.docker
Can 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.

Terminal window
mkdir -p -m 700 ~/.secrets
( umask 077; head -c 12 /dev/urandom | od -An -tx1 | tr -d ' \n' > ~/.secrets/regpass )
mkdir auth
htpasswd -B -i -n alice < ~/.secrets/regpass > auth/htpasswd
docker 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:82f6ff4a7f982960c8aa51617fea3aabc485df6e55cce80d22deb1de36f1bc3c

The 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.

build.pkr.hcl
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:

Terminal window
export PKR_VAR_registry_username=alice
export 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:

Terminal window
( umask 077; { printf 'user = "alice:'; cat ~/.secrets/regpass; echo '"'; } > ~/.secrets/curlrc )
curl -s -K ~/.secrets/curlrc localhost:5001/v2/myapp/tags/list

The 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: 1

With 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: 1

When 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.

OptionTypeDescription
loginboolLog in before the push
login_serverstringRegistry address
login_usernamestringUser name
login_passwordstringPassword or token
ecr_loginboolAWS ECR authentication
keep_input_artifactboolKeep 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.

build.pkr.hcl
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.

06-exemple-complet.pkr.hcl
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.

Terminal window
mkdir -p output
packer build -var "app_version=2.1.0" -var "build_number=${CI_BUILD_NUMBER:-local}" \
06-exemple-complet.pkr.hcl

With 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.

SymptomCauseSolution
Unknown artifact type: packer.docker with docker-tagThe source exports a file (export_path), not an imageUse a commit = true source, or place docker-tag after docker-import
Archive checksum different from the expected onecompress and checksum are in separate post-processor blocksGroup them in a post-processors block
login attempt to ... failed with status: 401 UnauthorizedWrong registry credentialsTest docker login by hand, check the variable
push access denied ... no basic auth credentialsPush without loginlogin = true with login_username and login_password
Unsupported attribute; This object does not have an attribute named ...Variable cited but not declaredAdd the variable block
manifest.json missing after the buildA provisioner failed before the post-processorFix the provisioner: no manifest is written on a failed build
sha256sum -c says did NOT match on Alpinebusybox's sha256sum reads the sum file differently from GNUCheck 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

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer