Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Variables and HCL

Packer Built-in Functions: Strings, Dates, Files, Collections

A tour of Packer's HCL functions: string and regex helpers, timestamp and formatdate, file and templatefile, collection and encoding functions, plus env, uuidv4 and secret lookups.

Packer's expression language has a library of built-in functions. You call them like upper("x") anywhere an expression is allowed: in arguments, locals, variable validation and provisioner content. Most are the same as Terraform's, with a few Packer-specific additions for the environment, unique IDs and secret managers. This lesson groups the functions you will actually use and shows examples you can check with packer console.

Packer cannot run on this site. The HCL examples are read-only, and the results quoted in comments are the ones the functions are specified to return. The Python stand-ins compute the same values for several of them so you can see what happens to the data.

How to try a function

Terminal
packer console
> upper("packer")
> formatdate("YYYYMMDD", "2025-01-31T12:30:00Z")

packer console reads your template too, so var.* and local.* are available. Functions are pure (same input, same output) except those that read the world: timestamp(), uuidv4(), env() and the secret-manager lookups.

String functions

Function Example Result
upper, lower, title upper("web") "WEB"
trimspace, trim, trimprefix, trimsuffix trimsuffix("img.qcow2", ".qcow2") "img"
replace replace("1.4.0", ".", "-") "1-4-0"
split, join split(",", "a,b,c") ["a", "b", "c"]
substr substr("abcdef", 0, 3) "abc"
format format("%s-%03d", "web", 7) "web-007"
regex regex("[0-9]+", "web42") "42"
regex_replace regex_replace("a-b c", "[- ]", "") "abc"
startswith, endswith startswith("ubuntu-24", "ubuntu") true
length length("abc") 3

regex() returns the match or fails with an error when nothing matches, so wrap it in can(...) or try(...) when the input may not match.

Date and time

HCL
locals {
  now       = timestamp()                                  # e.g. "2025-01-31T12:30:00Z" (changes every call)
  compact   = regex_replace(timestamp(), "[- TZ:]", "")    # "20250131123000"
  day       = formatdate("YYYY-MM-DD", timestamp())        # "2025-01-31"
  build_tag = formatdate("YYYYMMDD-hhmm", timestamp())     # "20250131-1230"
}

timestamp() is evaluated when Packer reads the template, so all sources in one run share a single value (useful: every cloud's image gets the same name). formatdate format letters: YYYY year, MM month, DD day, hh hour (24 h), mm minute, ss second, quoted text in single quotes. timeadd(ts, "24h") shifts a time, handy for expiry tags.

HCL
tags = {
  ExpiresOn = formatdate("YYYY-MM-DD", timeadd(timestamp(), "720h"))
}

A date stand-in

This Python stand-in mirrors regex_replace and formatdate on a fixed timestamp, so the results are deterministic.

Python Stand-in: timestamp and formatdate

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.

Numbers and conversion

min(1, 2), max(...), ceil(2.1) (3), floor(2.9) (2), abs(-4), pow(2, 3). Type conversion: tostring, tonumber, tobool, tolist, toset, tomap. Use can(expr) (returns bool) and try(expr, fallback) (returns the first expression that works) for tolerant code:

HCL
locals {
  port = try(tonumber(var.port_text), 8080)
}

Collection functions

Function Meaning
length(x) Number of elements
contains(list, v) Is v in the list?
concat(a, b) Join lists
merge(m1, m2) Combine maps; later wins
lookup(map, key, default) Safe map lookup
keys(map), values(map) Keys or values
element(list, i) Item i, wraps around
index(list, v) Position of v
distinct, sort, reverse, flatten, slice List shaping
zipmap(keys, values) Build a map from two lists
HCL
locals {
  env_size = lookup({ dev = "t3.micro", prod = "m6i.large" }, var.env, "t3.small")
  all_ports = distinct(concat([22, 80], var.extra_ports))
}

Encoding functions

jsonencode(value) / jsondecode(text) convert between HCL values and JSON, yamlencode writes YAML, base64encode / base64decode handle Base64, urlencode encodes URL components, textencodebase64 handles other character sets. They are the safe way to produce a JSON or YAML file inside the image:

HCL
provisioner "file" {
  content     = jsonencode({ environment = var.env, version = var.app_version })
  destination = "/tmp/app-config.json"
}

Writing JSON with jsonencode avoids quoting mistakes that creep into hand-built echo '{"a": ...}' shell commands.

File functions

Function Meaning
file(path) Read a file as a string
fileexists(path) Does it exist?
filebase64(path) Read as Base64
templatefile(path, vars) Render a template file
dirname, basename, abspath Path helpers
fileset(dir, pattern) Set of matching files

Paths are relative to the current working directory unless you build them with path.root: file("${path.root}/files/motd.txt").

templatefile

TEXT
# files/app.service.pkrtpl.hcl
[Service]
ExecStart=/opt/app/bin/app --port ${port}
%{ for key, value in env ~}
Environment=${key}=${value}
%{ endfor ~}
HCL
provisioner "file" {
  content = templatefile("${path.root}/files/app.service.pkrtpl.hcl", {
    port = var.app_port
    env  = { APP_ENV = var.env, LOG_LEVEL = "info" }
  })
  destination = "/tmp/app.service"
}

Template files use the same ${...} and %{ ... } syntax as strings. The ~ trims surrounding whitespace so the output has no blank lines. Python's string.Template or an f-string loop can mimic it:

Python Stand-in: what templatefile renders

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.

Packer-specific functions

Function Meaning
env("NAME") Read an environment variable (returns an empty string if unset, so validate it). Prefer PKR_VAR_* for inputs
uuidv4(), uuidv5(namespace, name) Random or name-based unique IDs
aws_secretsmanager("name", "key") Read a secret from AWS Secrets Manager (also the amazon-secretsmanager data source)
vault("path", "key") Read a secret from HashiCorp Vault
consul_key("key") Read a Consul KV value
sha256, sha512, md5, bcrypt Hash helpers
legacy_isotime, legacy_strftime, ... Compatibility helpers for migrated JSON templates; avoid in new code

Prefer the data source form for secrets and cloud lookups (next lesson): data sources are evaluated at a well-defined time and give you typed output. Treat env() carefully: an unset variable silently becomes an empty string, so check it in a validation-style local.

HCL
locals {
  run_id = uuidv4()
}

Remember that uuidv4() is a new random value on each evaluation; store it in a local if you need a stable value within the run.

Putting it together: an image name

HCL
variable "image_prefix" {
  type    = string
  default = "web"
}
variable "app_version" { type = string }

locals {
  stamp     = formatdate("YYYYMMDD-hhmm", timestamp())
  clean_ver = replace(var.app_version, ".", "-")
  image     = lower(format("%s-%s-%s", var.image_prefix, local.clean_ver, local.stamp))
}
# web-1-4-0-20250131-1230

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does regex_replace(timestamp(), "[- TZ:]", "") produce?

    It removes hyphens, spaces, T, Z and colons, leaving only digits.
  2. 2. Why is timestamp() convenient for multi-cloud builds?

    Packer evaluates it when reading the template, giving all sources one consistent value.
  3. 3. Which function reads a file and fills in ${...} placeholders from a map?

    templatefile(path, vars) renders a template file with the supplied variables.
  4. 4. What is the safest way to get a number from user text, with a fallback?

    try returns the first expression that evaluates without error.
  5. 5. Why prefer jsonencode over a hand-written echo of JSON?

    jsonencode produces valid JSON from HCL values, whatever characters they contain.

Summary

  • Functions are called as name(args) in any expression; test them with packer console.
  • Everyday groups: string and regex, date (timestamp, formatdate, timeadd), collections (merge, lookup, concat), encoding (jsonencode), files (file, templatefile).
  • can and try make expressions tolerant; env, uuidv4, vault and secret-manager functions read from outside and need care.
  • timestamp() gives one consistent value per run; uuidv4() is random on every call, so keep it in a local.
  • Use templatefile and jsonencode instead of fragile shell quoting.

Next: Data sources and sensitive values