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

Packer variables, locals and functions

By updated

Improve this page

Logo Packer

A Packer template is parameterized with four elements. The input variables (variable) receive values from the outside. The locals (locals) compute values from them. The functions transform these values, and the data sources (data) read external information. This lesson is for anyone who already knows how to write a template and build an image. It shows how to reuse the same template for several environments, how to predict which value wins, and how to read the errors Packer returns when a variable is missing or invalid.

What you will learn

  • Declare typed variables and add a validation rule to them.
  • Provide values with -var, PKR_VAR_, -var-file and the *.auto.pkrvars.hcl files.
  • Predict which value wins when a variable is defined several times.
  • Compute values with locals and the built-in functions.
  • Read a data source and check it with packer validate -evaluate-datasources.
  • Recognize variable errors from their message.

Prerequisites

Why parameterize a Packer template?

A template without variables must be copied for each environment: one copy for development, one for staging, one for production. Each change then has to be repeated in the three files, and an omission creates a difference that nobody wanted.

With variables, there is a single template, and each environment provides its values through a file or the command line. The template becomes a recipe, and the values are the ingredients of the environment. These value files carry the .pkrvars.hcl suffix. To compare this mechanism with Terraform's, see Variables and locals: what Terraform and Packer add to HCL (in French).

How do I declare and use an input variable?

An input variable is a parameter of the template, declared by a variable block and read with var.name. The name is unique in the template. The attributes in the table are all optional.

AttributeRole
typeType of the value: string, number, bool, list, map, object
defaultDefault value, which makes the variable optional
descriptionDocumentation of the variable
sensitiveIf true, Packer replaces the value with <sensitive> in what it displays
validationRule that refuses certain values

A variable without default is required. If no value is provided, Packer stops with Error: Unset variable "name", which the validation section shows further down.

Which types should you pick for a variable?

Choosing a type lets Packer refuse an inconsistent value before the build. The simple types are string (text), number and bool (true or false).

variable "app_version" {
type = string
default = "1.0.0"
description = "Version de l'application"
}
variable "timeout_seconds" {
type = number
default = 300
description = "Délai maximal du build en secondes"
}
variable "enable_debug" {
type = bool
default = false
description = "Activer les traces de debug"
}

Complex types group several values: a list of packages, a set of labels, a configuration.

variable "packages_to_install" {
type = list(string)
default = ["curl", "jq", "vim"]
description = "Liste des paquets à installer"
}
variable "labels" {
type = map(string)
default = {
maintainer = "devops@example.com"
environment = "development"
}
description = "Labels à ajouter à l'image"
}
variable "instance_config" {
type = object({
size = string
count = number
public = bool
})
default = {
size = "small"
count = 1
public = false
}
description = "Configuration de l'instance"
}

A map accepts any keys, but all its values have the same type. An object has a fixed structure: known keys, of possibly different types.

To check what Packer has read, packer inspect . lists the variables with their value. Structures appear there as text:

[...]
var.labels: "{\n \"environment\" = \"development\"\n \"maintainer\" = \"devops@example.com\"\n}"
var.packages_to_install: "[\n \"curl\",\n \"jq\",\n \"vim\",\n]"
var.timeout_seconds: "300"
[...]

How do I use a variable in a template?

A variable is read with var.name, in a string by interpolation ("${var.name}") or directly in an expression. The example reads a starting image, labels and a list of packages. The image is pinned by its digest in the default value of the base_image variable.

variable "base_image" {
type = string
default = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf"
description = "Image de départ, épinglée par digest"
}
source "docker" "example" {
image = var.base_image
commit = true
# Turn the labels map into LABEL instructions
changes = [for k, v in var.labels : "LABEL ${k}=${v}"]
}
build {
sources = ["source.docker.example"]
provisioner "shell" {
# Join the list of packages into a single string
inline = ["apk add --no-cache ${join(" ", var.packages_to_install)}"]
}
}

This excerpt replaces the source and build blocks of the template of the previous lessons: the packer block that declares the docker plugin stays in place. commit = true is required: with the docker builder, without commit, discard or export_path, validation fails with No instructions given for handling the artifact; expected commit, discard, or export_path. After packer init ., packer validate . must answer The configuration is valid.

How do I reject an invalid value?

A validation block contains a condition (a boolean expression) and an error_message displayed when it is false. Packer evaluates them before the build and refuses the value as soon as a rule fails. Several validation blocks can coexist on the same variable.

variable "environment" {
type = string
description = "Environnement cible (dev, staging, prod)"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "L'environnement doit être 'dev', 'staging' ou 'prod'."
}
}
variable "project_name" {
type = string
description = "Nom du projet (alphanumériques et tirets)"
validation {
condition = length(var.project_name) >= 3 && length(var.project_name) <= 20
error_message = "Le nom doit contenir entre 3 et 20 caractères."
}
validation {
condition = can(regex("^[a-zA-Z][a-zA-Z0-9-]*$", var.project_name))
error_message = "Le nom doit commencer par une lettre."
}
}
variable "api_token" {
type = string
sensitive = true
description = "Jeton d'API"
}

The can() function returns true if the expression passed to it evaluates without error, which makes it possible to test a regular expression. Run with no value at all, the validation flags each required variable:

Error: Unset variable "project_name"
A used variable must be set or have a default value; see
https://packer.io/docs/templates/hcl_templates/syntax for details.
[...]

With a refused value (-var environment=test), the message displayed is that of the rule, followed by the location of the rule in the file:

Error: Invalid value for cmd variable
on line 0:
(source code not available)
L'environnement doit être 'dev', 'staging' ou 'prod'.
This was checked by the validation rule at variables.pkr.hcl:24,3-13.

The line number depends on your file. A two-character project name (-var project_name=ab) fails with "Le nom doit contenir entre 3 et 20 caractères.", and project_name=1a triggers both rules: Packer displays both messages, because it evaluates all the validation blocks of the variable.

A value that does not have the right type is refused with a different message, which cites no rule:

Error: Invalid argument value for -var variable
The received arg value for timeout_seconds is not compatible with the variable's
type constraint: a number is required.

With correct values (-var environment=dev -var project_name=demo -var api_token=jeton-de-test), packer validate . answers The configuration is valid.

How do I hide a secret value?

With sensitive = true, Packer replaces the value of the variable with <sensitive> in what it displays: the output of packer inspect, but also that of a packer build. With no value provided, packer inspect displays <unknown>.

[...]
var.api_token: "<sensitive>"
[...]

During a build, a shell-local or shell script that prints the variable also produces <sensitive> in place of the value:

==> docker.alpine: Running local shell script: /tmp/packer-shell2201343389
==> docker.alpine: secret-vu=<sensitive>
==> docker.alpine: Provisioning with shell script: /tmp/packer-shell2106823315
==> docker.alpine: dans-limage=<sensitive>

This masking only applies to the display. The template still reads the real value: the script receives it in clear, and it can write it wherever it wants. Pass a secret through an environment variable, and never write it in a versioned file.

The replacement is done on the text, word for word. With a short value, Packer also masks pieces of its own messages: with -var api_token=x, the message "executing a build" is displayed e<sensitive>ecuting a build, and with api_token=secret, the name secret_hash is displayed <sensitive>_hash. So choose long, unusual secrets, and do not give a local a name that contains the value.

How do I provide variable values?

Packer accepts five sources of values. They range from the simplest, a command option, to the most structured, one file per environment.

Pass a value with -var

The -var option sets a value on the command line, for a test or for a value that changes at every build. A list or a map is written as in the examples below, between single quotes so that the shell does not touch the double quotes.

Terminal window
packer build -var="app_version=2.0.0" .
packer build -var='packages_to_install=["curl","jq"]' .
packer build -var='labels={"env":"prod","team":"backend"}' .

To see how Packer interpreted these values, packer console displays them:

Terminal window
echo 'var.labels' | packer console -var 'labels={"env":"prod","team":"backend"}' .
{
"env" = "prod"
"team" = "backend"
}

A -var option that cites a variable absent from the template is refused with Error: Undefined -var variable, detailed in the lesson Install Packer.

Pass a value through an environment variable

Packer reads the environment variables that start with PKR_VAR_. This method suits CI/CD pipelines, where secrets are injected by the environment. Locally, a secret is typed without being displayed, so that it does not stay in the shell history:

Terminal window
read -rs PKR_VAR_api_token && export PKR_VAR_api_token
export PKR_VAR_environment="prod"
packer build .

The name must respect the case of the variable: with a variable image_tag whose default is 3.20, PKR_VAR_Image_Tag=9 is ignored (the value stays 3.20) and PKR_VAR_image_tag=9 is taken into account (the value becomes 9).

Pass values through a .pkrvars.hcl file

A .pkrvars.hcl file contains only assignments. It describes the stable values of an environment:

dev.pkrvars.hcl
environment = "dev"
project_name = "demo"
packages_to_install = [
"curl",
"jq",
"vim",
"git"
]
labels = {
Team = "backend"
Project = "demo-app"
}

-var-file loads the file:

Terminal window
packer build -var-file="dev.pkrvars.hcl" .

A variable present in the file but declared nowhere does not make Packer fail: it displays a warning that suggests the block to add. You only see this warning in a folder where packages_to_install is not declared. If you reused the declaration from the section on types, remove it to trigger it.

Warning: Undefined variable
The variable "packages_to_install" was set but was not declared as an input
variable.
To declare variable "packages_to_install" place this block in one of your
.pkr.hcl files, such as variables.pkr.hcl
[...]

Files named *.auto.pkrvars.hcl are loaded without -var-file. They serve for the default values of the project:

  • Répertoiremon-projet/
    • build.pkr.hcl
    • variables.pkr.hcl
    • defaults.auto.pkrvars.hcl
    • prod.pkrvars.hcl

In this tree, defaults.auto.pkrvars.hcl is loaded with no option, whereas prod.pkrvars.hcl needs -var-file=prod.pkrvars.hcl.

Which value wins when a variable is defined several times?

When the same variable receives several values, the highest-priority source wins. With Packer 1.16.2, the order is the following, from weakest to strongest:

RankSourceIf several
1default valueOnly one
2Environment variable PKR_VAR_nameOnly one
3*.auto.pkrvars.hcl filesAlphabetical order: the last one wins
4-var-file optionsCommand line order: the last one wins
5-var optionsAlways highest priority

Each source replaces the previous one, from default up to -var. Between two *.auto.pkrvars.hcl files, the last one in alphabetical order wins. Between two -var-file options, it is the last one on the command line: by swapping their order, the other file wins.

The Packer documentation presents -var and -var-file as evaluated in command line order. With Packer 1.16.2, this is not the case: a -var option wins even when it is written before -var-file, the position makes no difference. The code of Packer 1.16.2 (hcl2template/types.variables.go) applies this order. Do not rely on the position of -var for another version.

This hierarchy lets you set a reasonable default value, override it per environment, then force it occasionally on the command line.

How do I compute values with locals?

A local is a value computed inside the template, from variables, other locals or functions. Unlike an input variable, it cannot be changed from the outside. A local avoids repeating an expression and gives a name to a computation.

The locals block (plural) groups several values:

locals {
# Build name with the date
build_id = "${var.project_name}-${formatdate("YYYYMMDD-hhmm", timestamp())}"
# Map of common labels
common_tags = {
Project = var.project_name
Environment = var.environment
ManagedBy = "packer"
BuildDate = timestamp()
}
# Choice depending on the environment
env_packages = var.environment == "prod" ? ["curl", "ca-certificates"] : ["curl", "jq", "vim"]
}

The local block (singular) defines a single value and accepts sensitive:

local "secret_hash" {
expression = md5("${var.project_name}-${var.environment}")
sensitive = true
}

A local is read with local.name. packer inspect . displays the computed locals, and the one that is sensitive appears masked. The command packer inspect -var environment=prod -var project_name=demo -var api_token=secret . displays:

[...]
local.build_id: "demo-20261119-1014"
[...]
local.<sensitive>_hash: "<sensitive>"

Look at the last line: the name of the local is displayed local.<sensitive>_hash. The value of api_token is here secret, and Packer replaces this word everywhere it displays it, including in the name secret_hash. The trap is described above, in the section on hiding a secret value.

Locals can reference each other, as long as none depends on itself, directly or through another local. With c = local.d and d = local.c, packer validate . stops:

Error: failed to prepare execution graph
An error occurred while building the graph for datasources/locals: 1 error
occurred:
* Cycle: local.d, local.c

The order in which you write the locals does not matter: a local can reference a local declared lower in the file. With a = "x" declared after b = "${local.a}-suffix", Packer gives x-suffix.

Which functions does Packer offer?

Packer provides functions to handle text, collections, dates and numeric values. They are used in locals, block arguments and packer console. To try an expression without running a build, pass it to packer console from a folder that contains a template:

Terminal window
echo 'strcontains("web-server", "web")' | packer console .

Which string functions should you use?

String functions change the case, replace, split and format. Each comment gives the result of the line.

locals {
project_lower = lower("Mon-Projet") # mon-projet
project_upper = upper("mon-projet") # MON-PROJET
slug = replace("mon projet", " ", "-") # mon-projet
prefix = substr("mon-projet", 0, 3) # mon
cleaned = trimspace(" hello ") # hello
trim_prefix = trimprefix("v1.0.0", "v") # 1.0.0
name = format("%s-build-%d", "app", 42) # app-build-42
tags = join(",", ["a", "b", "c"]) # a,b,c
parts = split(",", "a,b,c") # ["a", "b", "c"]
}

Which functions appeared in 1.12 and 1.13?

Some functions only exist in recent versions of Packer. A missing function answers Call to unknown function, which gives a simple test to run before using a recent function. The table gives the availability per version:

Function1.11.21.12.01.13.0
strcontains, alltrue, anytrueunknownavailableavailable
startswith, endswith, sumunknownunknownavailable

The other functions of the lesson, such as trimprefix, exist from 1.11.2. With Packer 1.16.2, all these functions exist.

locals {
is_web = strcontains("web-server", "web") # true
is_v1 = startswith("v1.2.0", "v1") # true
is_tar = endswith("file.tar.gz", ".tar.gz") # true
all_positive = alltrue([for n in [1, 2, 3] : n > 0]) # true
has_five = anytrue([for n in [1, 5] : n == 5]) # true
total = sum([1, 2, 3, 4, 5]) # 15
}

Which collection functions should you use?

Collection functions work on lists and maps. Each comment gives the result of the line.

locals {
liste = ["a", "b", "c", "a"]
config = { port = "8080", host = "0.0.0.0" }
count = length(local.liste) # 4
has_b = contains(local.liste, "b") # true
merged = concat(["x"], local.liste) # ["x", "a", "b", "c", "a"]
unique = distinct(local.liste) # ["a", "b", "c"]
flat = flatten([["a", "b"], ["c"]]) # ["a", "b", "c"]
keys = keys(local.config) # ["host", "port"]
vals = values(local.config) # ["0.0.0.0", "8080"]
full = merge(local.config, { debug = "true" }) # three keys
port = lookup(local.config, "port", "3000") # 8080
ssl = lookup(local.config, "ssl", "false") # false
result = coalesce("", null, "valeur") # valeur
}

How do I format a date with formatdate?

formatdate formats a date. timestamp() returns the current instant in RFC 3339 format, for example 2026-11-19T09:55:00Z. In the formatdate format, the case changes the meaning: hh means the hour on a 24-hour clock and HH the hour on a 12-hour clock. On a fixed date, 2026-02-14T15:30:05Z, the difference shows with packer console: each expression below is passed through echo '<expression>' | packer console ., and the result follows.

formatdate("hh:mm:ss", "2026-02-14T15:30:05Z")
15:30:05
formatdate("HH:mm:ss", "2026-02-14T15:30:05Z")
03:30:05
formatdate("YYYYMMDD-hhmm", "2026-02-14T15:30:05Z")
20260214-1530
formatdate("YYYYMMDD-HHmm", "2026-02-14T15:30:05Z")
20260214-0330

For an ISO 8601 timestamp, use hh:

locals {
iso = formatdate("YYYY-MM-DD'T'hh:mm:ssZ", timestamp())
filename = "build-${formatdate("YYYYMMDD-hhmm", timestamp())}.log"
}
CodeMeaning
YYYYFour-digit year
MMTwo-digit month
DDTwo-digit day
hhHour on a 24-hour clock
HHHour on a 12-hour clock
mmMinutes
ssSeconds

Which hashing and encoding functions should you use?

These functions transform a value: checksum, encoding, JSON, web address. Each comment gives the result of the line.

locals {
hash_md5 = md5("hello") # 5d41402abc4b2a76b9719d911017c592
hash_sha = sha256("hello") # 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
encoded = base64encode("Hello World") # SGVsbG8gV29ybGQ=
decoded = base64decode("SGVsbG8gV29ybGQ=") # Hello World
json = jsonencode({ name = "app", version = "1.0" }) # {"name":"app","version":"1.0"}
safe = urlencode("hello world") # hello+world
id = uuidv4() # a different UUID on each call
}

Note that urlencode replaces the space with + and not %20. The numeric functions min(1, 5, 3) (1), max(1, 5, 3) (5), abs(-5) (5), ceil(3.2) (4) and floor(3.8) (3) return the values given in parentheses.

How do I read external data with a data source?

A data source reads information outside the template, for example an HTTP response, and exposes it in the form data.TYPE.NAME.attribute. It is declared with a data block. The example reads a JSON file over HTTP: replace the URL with that of a real configuration file of your project, because the address below is an illustration.

variable "config_url" {
type = string
default = "https://raw.githubusercontent.com/example/config/main/app.json"
description = "URL du fichier de configuration (à remplacer)"
}
data "http" "app_config" {
url = var.config_url
request_headers = {
Accept = "application/json"
}
}
locals {
config = jsondecode(data.http.app_config.body)
version = local.config.version
}

A data source does not run during a plain packer validate. With an unreachable address, packer validate . answers The configuration is valid., whereas the -evaluate-datasources option actually runs the read and makes the command fail:

Terminal window
packer validate -var config_url=http://127.0.0.1:9/nope.json -evaluate-datasources .

The address 127.0.0.1:9/nope.json, where nothing listens, replaces here the default URL of the example. The command fails:

Error: Datasource.Execute failed: Get "http://127.0.0.1:9/nope.json": dial tcp 127.0.0.1:9: connect: connection refused
on d.pkr.hcl line 7:
(source code not available)

Packer cites the file that holds the data block (here d.pkr.hcl) and its line: on your machine, these are the name and the line of your own file.

Against an HTTP server that returns {"version":"2.3.1","name":"app"}, the same command succeeds: the server receives a GET /app.json request with the Accept: application/json header, and packer inspect displays the evaluated locals:

[...]
local.config: "{\n \"name\" = \"app\"\n \"version\" = \"2.3.1\"\n}"
local.version: "2.3.1"
[...]

A local can read a data source, and a data source can also read a local: url = local.u validates correctly from Packer 1.12.0. With Packer 1.11.2, the same configuration fails with Unsupported attribute: do not use this form if you must stay on a version earlier than 1.12.

How do I put variables, locals and functions together in a full example?

This example builds a Docker image parameterized by environment: the image name, the labels, the choice of packages and the version come from variables and locals. It is built in five steps.

The app_version variable follows semantic versioning, or semver: three numbers separated by dots, MAJOR.MINOR.PATCH, optionally followed by a pre-release after a hyphen, such as 1.0.0-dev or 1.0.0-rc.1. The rule in the example is a simplified version of it: it does not handle semver's +build suffix.

  1. Create the project folder:

    Terminal window
    mkdir -p packer-variables-demo && cd packer-variables-demo
  2. Create variables.pkr.hcl, which declares the variables and their rules:

    variable "app_name" {
    type = string
    default = "myapp"
    description = "Nom de l'application"
    validation {
    condition = can(regex("^[a-z][a-z0-9-]*$", var.app_name))
    error_message = "Le nom doit être en minuscules."
    }
    }
    variable "app_version" {
    type = string
    default = "1.0.0"
    description = "Version semver X.Y.Z, avec pré-version facultative (1.0.0-dev)"
    validation {
    condition = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?$", var.app_version))
    error_message = "Format X.Y.Z requis, avec un suffixe facultatif comme -dev ou -rc.1."
    }
    }
    variable "environment" {
    type = string
    default = "dev"
    validation {
    condition = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environnement invalide."
    }
    }
    variable "packages_by_env" {
    type = map(list(string))
    default = {
    dev = ["curl", "jq", "vim", "git"]
    staging = ["curl", "jq", "git"]
    prod = ["curl", "ca-certificates"]
    }
    }
  3. Create build.pkr.hcl, which computes the locals and describes the build:

    packer {
    required_version = ">= 1.12.0"
    required_plugins {
    docker = {
    version = "~> 1.1"
    source = "github.com/hashicorp/docker"
    }
    }
    }
    locals {
    image_name = "${var.app_name}-${var.environment}"
    build_date = formatdate("YYYY-MM-DD", timestamp())
    build_id = substr(md5("${var.app_name}-${timestamp()}"), 0, 8)
    env_packages = lookup(var.packages_by_env, var.environment, var.packages_by_env["dev"])
    is_production = var.environment == "prod"
    labels = {
    "app.name" = var.app_name
    "app.version" = var.app_version
    "app.environment" = var.environment
    "app.build.date" = local.build_date
    }
    }
    source "docker" "app" {
    image = "alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf"
    commit = true
    changes = [for k, v in local.labels : "LABEL ${k}=${v}"]
    }
    build {
    name = local.image_name
    sources = ["source.docker.app"]
    provisioner "shell" {
    inline = [
    "echo 'Build: ${local.image_name} v${var.app_version}'",
    "echo 'ID: ${local.build_id}'",
    "echo 'Production: ${local.is_production}'",
    "apk add --no-cache ${join(" ", local.env_packages)}"
    ]
    }
    }
  4. Create one value file per environment. The app_version rule accepts 1.0.0 as well as 1.0.0-dev:

    dev.pkrvars.hcl
    app_name = "myapp"
    app_version = "1.0.0-dev"
    environment = "dev"
    prod.pkrvars.hcl
    app_name = "myapp"
    app_version = "1.0.0"
    environment = "prod"
  5. Install the plugin, then validate both environments. Both packer validate commands must answer The configuration is valid.:

    Terminal window
    packer init .
    packer validate -var-file=dev.pkrvars.hcl .
    packer validate -var-file=prod.pkrvars.hcl .

The -dev suffix of 1.0.0-dev is a pre-release: the rule ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ accepts it, with or without the suffix. In the HCL file, backslashes are doubled (\\.) because HCL interprets them inside a string. A version that does not follow this format is refused. To see this refusal, create a third file, mauvais.pkrvars.hcl, with version v1.0, which has only two numbers and starts with a v:

mauvais.pkrvars.hcl
app_name = "myapp"
app_version = "v1.0"
environment = "dev"
Terminal window
packer validate -var-file=mauvais.pkrvars.hcl .

This command fails, and that is the expected result (exit code 1). Start with the first line: it says the value comes from a value file. The message then cites that file and the faulty line, followed by the text of the rule and the place of the rule in variables.pkr.hcl. The faulty line is line 3: the comment takes line 1, app_name line 2 and app_version line 3.

Error: Invalid value for varfile variable
on mauvais.pkrvars.hcl line 3:
(source code not available)
Format X.Y.Z requis, avec un suffixe facultatif comme -dev ou -rc.1.
This was checked by the validation rule at variables.pkr.hcl:17,3-13.

Line number 17 is that of the validation block of app_version in variables.pkr.hcl. Fix app_version in mauvais.pkrvars.hcl (for example "1.0.0") and the validation passes again.

packer inspect -var-file=prod.pkrvars.hcl . displays the locals computed for production:

[...]
local.build_date: "2026-11-19"
local.build_id: "78348e8c"
local.env_packages: "[\n \"curl\",\n \"ca-certificates\",\n]"
local.image_name: "myapp-prod"
local.is_production: "true"
[...]

The image build is started with packer build -var-file=prod.pkrvars.hcl .. Look in its output for the three lines Build: myapp-prod v1.0.0, ID: followed by eight hexadecimal characters and Production: true, then the last line Imported Docker image: sha256:.... The labels are checked on the built image, by passing the command the sha256:... identifier from this last line:

Terminal window
docker image inspect --format '{{json .Config.Labels}}' <identifiant de l'image>
{"app.build.date":"2026-11-19","app.environment":"prod","app.name":"myapp","app.version":"1.0.0"}

How do I read variable errors?

The messages below are those of Packer 1.16.2. Each row gives the exact start of the message, its cause and the fix.

MessageCauseFix
Error: Unset variable "X"A variable without default received no valuePass -var, PKR_VAR_X or a value file
Error: Invalid value for cmd variableA validation rule refuses a value passed by -varRead the message of the rule, fix the value
Error: Invalid value for varfile variableA validation rule refuses a value from a .pkrvars.hcl fileFix the value at the line indicated
Error: Invalid argument value for -var variable with a number is required.The type of the value does not match the variableGive a value of the right type
Error: Undefined -var variable-var cites a variable the template does not declareDeclare the variable
Warning: Undefined variableA value file defines a variable that is not declaredDeclare the variable, or remove the line
Cycle: local.d, local.cLocals reference each otherBreak the dependency loop
Error: Missing pluginsThe plugin is not installedRun packer init .
Error: Call to unknown functionThe function does not exist in this version of PackerUpdate Packer (see the table of versions)
Error: Datasource.Execute failed-evaluate-datasources could not read the sourceCheck the URL, the network and the remote service

To see the values Packer kept, packer inspect . lists the variables and the locals, and packer console evaluates a single expression.

Key takeaways

A template is parameterized with four elements. The input variables receive values from the outside, the locals compute from them, the functions transform the values and the data sources read external data. A type and a validation block refuse an inconsistent value before the build, with a message that cites the rule.

A variable receives its value, from weakest to strongest, from default, from PKR_VAR_name, from the *.auto.pkrvars.hcl files, from the -var-file options then from -var, which always wins, even when placed before -var-file. The name of an environment variable respects the case.

Locals reference each other freely, in no imposed order, but not in a cycle. The functions strcontains, alltrue and anytrue need Packer 1.12 or later, startswith, endswith and sum need 1.13. In formatdate, hh gives the hour on a 24-hour clock and HH the hour on a 12-hour clock. A data source does not run in packer validate alone: it needs -evaluate-datasources.

Knowledge check

These questions cover the variables, their priority, the locals, the functions and the error messages the lesson has just presented.

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