Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Packer CLI Commands and Build Flags

A practical tour of the Packer command line: init, fmt, validate, build, console, inspect, plugins, hcl2_upgrade, build flags like -only and -on-error, logging and exit codes.

The packer program has a short list of commands. You will use five of them every day, and the rest when you debug or migrate. This lesson explains each command, the most useful flags for packer build, how to read logs, and what exit codes mean so your scripts and CI pipelines can react correctly.

Packer cannot run on this site, so all commands here are read-only. Examples describe what you will see instead of pasting output, which varies by version and platform. A Python stand-in at the end models how a CLI turns flags into a decision.

The command list at a glance

Command Purpose
packer init Install the plugins a template requires
packer fmt Format files to the canonical style
packer validate Check a template without building
packer build Run builds and produce artifacts
packer console Evaluate expressions interactively
packer inspect Show a template's variables, sources and builds
packer plugins Manage installed plugins (install, installed, required, remove)
packer hcl2_upgrade Convert a legacy JSON template to HCL2
packer fix Update older JSON templates to a newer JSON syntax
packer version Print the version

Every command that takes a template accepts either a directory (all *.pkr.hcl and *.pkr.json files in it are loaded together) or a single file. Using . for "the current directory" is the usual style.

init

Terminal
packer init .
packer init -upgrade .      # move to the newest plugin version that matches your constraint

Installs plugins from required_plugins. With -upgrade Packer picks the newest version allowed by your version constraint instead of keeping what is installed.

fmt

Terminal
packer fmt .                # rewrite files in place
packer fmt -check .         # exit non-zero if any file needs formatting (good for CI)
packer fmt -diff .          # show what would change
packer fmt -recursive .     # include sub-folders

validate

Terminal
packer validate .
packer validate -var 'region=eu-west-1' .
packer validate -var-file=prod.pkrvars.hcl .
packer validate -syntax-only .    # skip checks that need variable values

Always pass the same -var and -var-file options you will use for build, otherwise required variables without defaults cause errors. -syntax-only is handy in a quick pre-commit hook.

build

Terminal
packer build .
packer build -var 'instance_type=t3.small' .
packer build -var-file=prod.pkrvars.hcl .
packer build -only='learn-packer.docker.ubuntu' .
packer build -except='*.vmware-iso.*' .

Selecting sources

-only and -except take patterns of the form buildname.sourcetype.sourcename, and * is a wildcard. They are how you build only the AWS image while testing, or everything except an expensive VMware image on a laptop.

Failure handling

-on-error decides what happens to the temporary machine when a step fails:

Value Behavior
cleanup (default) Destroy the machine
abort Leave it running so you can inspect it (you must delete it yourself and may pay for it)
ask Prompt you what to do
run-cleanup-provisioner Run the template's error-cleanup provisioner, then clean up

Other useful flags

  • -debug: pause before every step and keep SSH keys so you can log in; slows builds on purpose.
  • -force: remove artifacts that already exist (for example local output folders) instead of failing.
  • -parallel-builds=N: limit how many sources build at the same time (0 means unlimited).
  • -color=false: no ANSI colors, best for CI logs.
  • -timestamp-ui: prefix every output line with a timestamp.
  • -machine-readable: print comma-separated machine output for scripts (it is a legacy format and not stable for every message, so prefer a manifest post-processor to find artifact IDs).

console

Terminal
packer console .

Opens a prompt where you can type expressions that use your variables and Packer's functions. It is the quickest way to test regex_replace, formatdate or lookup before putting them in a template. Example session (what you type, not output): upper("hello"), var.region. You can also pass a single expression by piping into it.

inspect

Terminal
packer inspect .

Lists input variables with their defaults, local variables, the sources and the builds in the template. Use it to answer "what does this template build and which variables must I supply?" without reading every file.

plugins

Terminal
packer plugins installed        # list installed plugin binaries
packer plugins required .       # list plugins a template needs
packer plugins install github.com/hashicorp/docker ">= 1.0.0"
packer plugins remove github.com/hashicorp/docker

Plugins and packer init covers constraints and sources in depth.

hcl2_upgrade and fix

Before HCL2 became the standard, templates were JSON. packer hcl2_upgrade template.json writes an HCL2 version next to it (named template.json.pkr.hcl). Review the result by hand: the converter makes the file valid but not elegant. packer fix upgrades old JSON templates to newer JSON conventions and is rarely needed today.

Logging and debugging

Packer prints a friendly UI to the terminal. For details use the log:

Terminal
PACKER_LOG=1 packer build .                      # bash, zsh
PACKER_LOG=1 PACKER_LOG_PATH=packer.log packer build .
POWERSHELL
$env:PACKER_LOG = "1"
$env:PACKER_LOG_PATH = "packer.log"
packer build .

The log is very detailed and may contain sensitive values, so never attach a raw log to a public bug report without redacting it. Variables marked sensitive are hidden in the normal UI, but plugins can still log secrets in debug mode.

Exit codes

packer build exits with 0 when every selected build succeeds and non-zero when any fails. fmt -check and validate follow the same rule. Scripts and CI systems rely on this, so avoid wrapping Packer in something that hides its status (such as packer build . | tee log without set -o pipefail).

Terminal
set -euo pipefail
packer fmt -check .
packer validate .
packer build -color=false .

A stand-in for flag handling

The next program is a Python stand-in that imitates how -only and -except patterns select sources. It uses fnmatch, which understands * like Packer's patterns do in this simplified model.

Python Stand-in: -only and -except patterns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A command cheat sheet as slides

Daily commands

init Get the plugins.
fmt Format the files.
validate Check without building.
build Make the image.

Run them in this order.

1 / 2

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which flag keeps the temporary machine running after a failed step so you can inspect it?

    -on-error=abort leaves the machine for debugging; you must delete it yourself afterwards.
  2. 2. You want a quick CI check that formatting is correct without changing files. Which command?

    packer fmt -check exits non-zero when files need formatting and does not rewrite them.
  3. 3. What is packer console for?

    console is an expression sandbox, ideal for testing functions such as regex_replace.
  4. 4. How do you build only the Amazon sources in any build?

    -only takes buildname.sourcetype.sourcename patterns with * as a wildcard.
  5. 5. Why should you pass the same -var-file to validate as to build?

    Required variables and variable-dependent checks need the same values you will build with.

Summary

  • The daily loop is init, fmt, validate, build; console, inspect and PACKER_LOG help when debugging.
  • -only and -except select sources with build.type.name patterns.
  • -on-error controls cleanup after failures; abort keeps the machine for inspection.
  • Pass the same -var and -var-file options to validate and build.
  • Exit codes are non-zero on failure, so keep them visible in scripts with set -o pipefail.
  • packer hcl2_upgrade converts legacy JSON templates to HCL2.

Next: Template anatomy