Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 36 ยท Concepts and Templates

Packer Template Anatomy: Blocks, Arguments, Expressions

Understand every top-level block in a Packer HCL2 template, how arguments and nested blocks differ, how references work and how Packer builds a plan from your files.

A Packer template is a set of text files written in HCL2, the HashiCorp Configuration Language also used by Terraform. HCL is small: it has blocks, arguments and expressions, and nothing else. Once you can read those three, any Packer template becomes readable. This lesson maps every top-level block you can write, and shows how references let one block use another.

Packer does not run on this site, so HCL is shown read-only. The Python programs are stand-ins that parse a simplified HCL subset to show the structure; they are not Packer's real parser.

Blocks, arguments and expressions

HCL
source "docker" "ubuntu" {          # block type, two labels, body in braces
  image  = "ubuntu:24.04"           # argument: name = expression
  commit = true

  changes = [                       # a list expression
    "ENV LANG=C.UTF-8",
  ]
}
  • A block has a type (source), zero or more labels ("docker", "ubuntu") and a body in { }.
  • An argument is name = expression inside a body. Arguments set values.
  • An expression can be a literal ("text", 42, true), a list [...], a map { key = "value" }, a reference (var.region), a function call (upper("x")) or a combination such as a template string "web-${var.env}".
  • Nested blocks appear inside a body, for example launch_block_device_mappings { ... } inside an AWS source. Unlike arguments, they have no = sign.
  • Comments: # and // for one line, /* ... */ for several.

Names use letters, digits, underscores and hyphens, and cannot start with a digit.

The top-level blocks

Block Purpose Count
packer { } Settings: required Packer version, required plugins At most one per template directory is typical
source "type" "name" { } A reusable builder configuration Any number
build { } Joins sources with provisioners and post-processors One or more
variable "name" { } An input variable Any number
locals { } Computed values for reuse Any number
data "type" "name" { } Read external data at build time Any number

Everything else (provisioners, post-processors, error-cleanup-provisioner, post-processors chains) lives inside a build block.

The packer block

HCL
packer {
  required_version = ">= 1.10.0"

  required_plugins {
    amazon = {
      version = ">= 1.3.0"
      source  = "github.com/hashicorp/amazon"
    }
    docker = {
      version = ">= 1.0.0"
      source  = "github.com/hashicorp/docker"
    }
  }
}

required_version makes Packer refuse to run with an incompatible version, which protects a team whose members have different installations. required_plugins lists plugins; the key (amazon, docker) is the local name you can use for matching types, as explained in Plugins and packer init.

source blocks

HCL
source "amazon-ebs" "ubuntu" {
  region        = "eu-west-1"
  instance_type = "t3.micro"
  source_ami    = "ami-0123456789abcdef0"
  ssh_username  = "ubuntu"
  ami_name      = "web-base"
}

The first label is the builder type (it must come from an installed plugin) and the second is your name for this configuration. The full address is source.amazon-ebs.ubuntu. A source describes where and how to start a machine. It says nothing about what to install.

build blocks

HCL
build {
  name    = "web"
  sources = ["source.amazon-ebs.ubuntu", "source.docker.ubuntu"]

  provisioner "shell" {
    inline = ["echo hello"]
  }

  post-processor "manifest" {
    output = "manifest.json"
  }
}

sources lists which sources to run. Each listed source produces its own machine and its own image, and the provisioners apply to all of them. The optional name becomes part of the build address (web.amazon-ebs.ubuntu) and is available in expressions as build.name.

Inside a build you can also write a source "source.docker.ubuntu" { ... } block instead of listing it in sources, which lets you give that source a different name for this build. See Source and build blocks.

References

Blocks refer to one another by address:

Reference Meaning
var.name Input variable
local.name Local value
source.type.name A source block (in sources)
data.type.name.attribute A data source's output
build.ID, build.Host, build.PackerRunUUID, ... Information about the running build
source.name, source.type Name and type of the source being built (inside a build)

Some build values only exist once a machine is running (for example the instance ID or build.Host), so they can be used in provisioners but not in source arguments.

HCL
variable "env" {
  type    = string
  default = "dev"
}

locals {
  image_name = "web-${var.env}"
}

source "docker" "app" {
  image  = "ubuntu:24.04"
  commit = true
}

build {
  sources = ["source.docker.app"]

  provisioner "shell" {
    inline = ["echo Building ${local.image_name} from ${source.name}"]
  }
}

Because all files in a directory are loaded together, var.env and local.image_name can be defined in any file; there is no import and no required file order.

Value types

  • string: "hello", with ${...} interpolation.
  • number: 3, 0.5.
  • bool: true, false.
  • list / tuple: ["a", "b"].
  • map / object: { Name = "web", Env = "prod" }.
  • null: means "not set" (the argument behaves as if omitted).

Heredocs hold multi-line text:

HCL
provisioner "shell" {
  inline = [<<-EOT
    set -eu
    echo "line one"
    echo "line two"
  EOT
  ]
}

<<- strips common leading indentation, so you can indent the body naturally.

A stand-in parser

To make the structure concrete, here is a simplified Python parser that reads block headers and arguments and prints the tree. It handles only the small subset used in the example (no heredocs, no multi-line lists). Real Packer uses a full HCL2 parser.

Python Stand-in: print the block tree of a template

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.

The nesting you see in the output (a provisioner block inside build) is exactly how Packer reads your files.

Style rules

  • Two-space indentation, aligned = signs within a group of arguments: packer fmt does it for you.
  • One concern per file: sources.pkr.hcl, build.pkr.hcl, variables.pkr.hcl. See Multi-file templates and JSON.
  • Prefer descriptive source names (ubuntu, windows, nodejs) and use name in build when you have several builds.
  • Keep secrets out of arguments. Use sensitive variables and environment-backed values (Data sources and sensitive values).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between an argument and a nested block?

    Arguments assign a value. Nested blocks group settings and are written like launch_block_device_mappings { ... }.
  2. 2. What do the two labels in source "docker" "ubuntu" mean?

    The first label selects the builder type from a plugin, the second is a name you choose; together they form source.docker.ubuntu.
  3. 3. How do you reference a local value named image_name?

    Locals are declared in a locals block but referenced with the singular local. prefix.
  4. 4. Where do provisioners belong?

    Provisioners and post-processors are part of a build, which applies them to every listed source.

Summary

  • HCL2 consists of blocks (type, labels, body), arguments (name = expression) and expressions.
  • Top-level blocks: packer, source, build, variable, locals and data.
  • A source says where and how to start a machine; a build says what to do with it.
  • References use var., local., source., data. and build. prefixes.
  • All files in a directory form one template; file names and order do not matter.

Next: Source and build blocks