Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Variables and HCL

Packer Locals and HCL Expressions: Conditionals, for, dynamic

Compute values in Packer with locals, template strings, conditionals, for expressions, splat, merge and dynamic blocks, and learn when to use a local instead of a variable.

Variables bring values in from outside. Locals compute values inside the template so you can name an expression once and reuse it. Together with HCL's expressions (conditionals, for loops, string templates, dynamic blocks) they let a template adapt to its inputs without copy-pasting. This lesson covers all of them with focused examples and Python equivalents.

Packer does not run on this site, so HCL is read-only and there is no real output. Each HCL example is paired with a Python stand-in that computes the same thing; use packer console on your own computer to check the real results.

Locals

HCL
variable "env"         { type = string }
variable "app_version" { type = string }

locals {
  timestamp  = regex_replace(timestamp(), "[- TZ:]", "")
  image_name = "web-${var.env}-${var.app_version}-${local.timestamp}"

  common_tags = {
    BuiltBy     = "packer"
    Environment = var.env
    Version     = var.app_version
  }
}

Use them as local.image_name. Locals may reference variables, other locals and functions; the order they are written in does not matter, but circular references are an error. Several locals blocks may exist in one template (names must be unique across all of them).

For a secret computed value, use the singular local block, which supports sensitive:

HCL
local "connection_string" {
  expression = "postgres://app:${var.db_password}@db.internal/app"
  sensitive  = true
}

Reference it as local.connection_string. As with variables, sensitive hides the value in Packer's output only.

Variable or local? If a user should be able to change it from the command line, make it a variable. If it is derived, make it a local. Defaults of variables must be literals, so anything computed goes in a local.

String templates

HCL
"web-${var.env}"                       # interpolation
"${var.region}-${local.timestamp}"
"$${literal}"                          # $$ produces a literal ${

Directives choose text conditionally or repeat it:

HCL
locals {
  banner = "%{ if var.env == "prod" }PRODUCTION%{ else }non-production%{ endif } image"
}

Heredocs are handy for generated scripts:

HCL
locals {
  motd = <<-EOT
    Image: ${local.image_name}
    Built: ${local.timestamp}
  EOT
}

Operators and conditionals

Kind Operators
Arithmetic + - * / %
Comparison == != < <= > >=
Logic `&&
Conditional condition ? when_true : when_false
HCL
locals {
  instance_type = var.env == "prod" ? "m6i.large" : "t3.micro"
  disk_size     = var.env == "prod" ? 50 : 20
  encrypt       = var.env != "dev"
}

Both branches of a conditional must have a compatible type. Use null when you want an argument to be unset:

HCL
source "amazon-ebs" "web" {
  kms_key_id = var.env == "prod" ? var.kms_key : null
}

Collections

HCL
locals {
  azs      = ["a", "b", "c"]
  first_az = local.azs[0]
  sizes    = { small = "t3.micro", large = "m6i.large" }
  chosen   = local.sizes["small"]       # or local.sizes.small
  all_tags = merge(local.common_tags, { Name = local.image_name })
}

merge() combines maps (later maps win). Use lookup(map, key, default) when a key may be missing.

for expressions

Transform or filter lists and maps:

HCL
locals {
  names   = ["web", "api", "worker"]

  upper   = [for n in local.names : upper(n)]                    # list -> list
  indexed = { for i, n in local.names : n => i }                 # list -> map
  long    = [for n in local.names : n if length(n) > 3]          # filter
  tagged  = { for k, v in local.common_tags : lower(k) => v }    # map -> map
}

Square brackets produce a list, curly braces produce a map (with =>). The optional if filters. The same comprehension idea exists in Python, which makes this easy to test:

Python Stand-in: HCL for expressions in Python

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.

Splat expressions

[for x in list : x.attr] has a shorthand, list[*].attr:

HCL
locals {
  disks      = [{ name = "root", size = 20 }, { name = "data", size = 100 }]
  disk_names = local.disks[*].name        # ["root", "data"]
}

dynamic blocks

Nested blocks cannot take a for expression directly. A dynamic block generates one nested block per element of a collection:

HCL
variable "disks" {
  type = list(object({
    device = string
    size   = number
  }))
  default = [
    { device = "/dev/sda1", size = 20 },
    { device = "/dev/sdf",  size = 100 },
  ]
}

source "amazon-ebs" "web" {
  # ...
  dynamic "launch_block_device_mappings" {
    for_each = var.disks
    content {
      device_name           = launch_block_device_mappings.value.device
      volume_size           = launch_block_device_mappings.value.size
      volume_type           = "gp3"
      delete_on_termination = true
    }
  }
}

Inside content the loop variable is named after the block (launch_block_device_mappings.value, and .key for the index or map key). Dynamic blocks are also available for provisioners' nested blocks. Use them when the number of blocks depends on input; for two fixed blocks, write them out for clarity.

A Python model of what the block generates:

Python Stand-in: what a dynamic block expands to

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.

Many sources

You cannot loop over source blocks. Write one source per platform and keep the shared steps in one build; use -only and -except to pick sources at run time (Source and build blocks).

Practical expressions for image names

HCL
locals {
  safe_version = replace(var.app_version, ".", "-")           # 1.4.0 -> 1-4-0
  image_name   = lower("${var.image_prefix}-${local.safe_version}")
  name_length_ok = length(local.image_name) <= 63
}

Check names with packer console: type local.image_name and press Enter to see the computed value, which is far faster than a full build.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a variable's default not contain a function call, while a local can?

    Defaults are literal values. Anything computed belongs in a local.
  2. 2. What does { for i, n in local.names : n => i } produce?

    Curly braces with => create a map; here names become keys and indexes become values.
  3. 3. How do you leave an argument unset in one branch of a conditional?

    null means the argument is treated as not set.
  4. 4. What is a dynamic block for?

    dynamic repeats a nested block based on for_each, using the block name as the iterator.
  5. 5. Where do you run a quick check of what local.image_name evaluates to?

    packer console evaluates expressions against your template's variables and locals.

Summary

  • locals name computed values; use the singular local block for a sensitive one.
  • Variables are inputs with literal defaults; locals are derived values that may use variables, functions and other locals.
  • Template strings use ${...} and %{ if } directives; conditionals use cond ? a : b, and null unsets an argument.
  • for expressions build lists or maps, splat ([*]) is the shortcut for attribute lists, merge() combines maps.
  • dynamic blocks generate repeated nested blocks from a collection; test expressions with packer console.

Next: Built-in functions