Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Variables and HCL

Packer Input Variables: Types, Defaults, Validation, Precedence

Parameterize Packer templates with input variables: types, defaults, descriptions, validation rules, sensitive values, var files, PKR_VAR environment variables and precedence.

A template that hard-codes a region, an instance type and a version number can only build one image. Input variables turn those constants into parameters, so the same template builds a development image, a production image or a copy for another region. This lesson explains how to declare variables, the type system, validation, sensitive values and the ways to supply values, including exactly which one wins when several are given.

Packer is not available on this site, so HCL and commands are read-only and no real output is shown. The Python stand-ins reproduce the precedence rules and a validation check so you can experiment with them.

Declaring a variable

HCL
variable "region" {
  type        = string
  default     = "eu-west-1"
  description = "AWS region where the image is built."
}

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

variable "app_version" {
  type        = string
  description = "Application version to bake into the image (no default: required)."
}

Arguments:

  • type: the accepted type (string, number, bool, lists, maps, objects, see below). If omitted, any type is accepted, but declaring one gives better error messages.
  • default: used when nobody supplies a value. A variable without a default is required: Packer stops and asks for it.
  • description: shown by packer inspect and in docs. Always write one.
  • sensitive: true hides the value in logs and UI output.
  • validation: rules the value must satisfy (below).

Use a variable with var.name:

HCL
source "amazon-ebs" "web" {
  region        = var.region
  instance_type = var.instance_type
  ami_name      = "web-${var.app_version}"
}

Variable blocks are separate from locals: variables are inputs (set from outside), locals are computed inside the template (Locals and expressions). Variables cannot reference other variables or functions in their default; only literals are allowed there. Use a local when you need to compute something from another variable.

Types

HCL
variable "ports"       { type = list(number) }
variable "tags"        { type = map(string) }
variable "features"    { type = set(string) }
variable "enable_ssm"  { type = bool }
variable "disk" {
  type = object({
    size = number
    type = string
  })
  default = {
    size = 20
    type = "gp3"
  }
}
Type Example value
string "eu-west-1"
number 20
bool true
list(string) ["a", "b"]
map(string) { Env = "prod" }
object({...}) { size = 20, type = "gp3" }
any whatever is given

Packer converts compatible values automatically (the string "20" becomes the number 20 for a number variable), and reports an error when it cannot.

Validation

HCL
variable "env" {
  type        = string
  description = "Deployment environment."

  validation {
    condition     = contains(["dev", "staging", "prod"], var.env)
    error_message = "env must be dev, staging or prod."
  }
}

variable "image_prefix" {
  type    = string
  default = "web"

  validation {
    condition     = can(regex("^[a-z][a-z0-9-]{2,30}$", var.image_prefix))
    error_message = "Use 3-31 lowercase letters, digits and hyphens, starting with a letter."
  }
}

condition is a bool expression using the variable; error_message is what the user sees. can(...) turns an error (a failed regex, a type conversion) into false. A variable can have several validation blocks. Validation runs during packer validate and packer build, before any machine is created, which saves time and money when someone passes a typo.

Supplying values

Ways to set a variable, from the lowest priority to the highest:

  1. default in the variable block.
  2. Environment variable PKR_VAR_<name>, for example PKR_VAR_region=us-east-1.
  3. Automatic variable files: any *.auto.pkrvars.hcl or *.auto.pkrvars.json in the template directory, loaded in alphabetical order.
  4. -var-file=path and -var 'name=value' options on the command line, applied in the order they appear; later ones override earlier ones.
Terminal
# environment
export PKR_VAR_app_version=1.4.0

# command line
packer build -var 'region=us-east-1' -var 'env=prod' .

# a variable file
packer build -var-file=values/prod.pkrvars.hcl .
HCL
# values/prod.pkrvars.hcl
region        = "eu-west-1"
instance_type = "t3.small"
env           = "prod"
tags = {
  Team = "platform"
  Cost = "web"
}

Variable files hold only assignments (no blocks). Lists and maps use HCL syntax; on the command line complex values need quoting for your shell, for instance -var 'ports=[80,443]'.

Variables that are set somewhere do not trigger errors; a required variable with no value anywhere does. In CI there is no keyboard, so a missing required variable fails the job immediately, which is what you want.

Precedence in a stand-in

This Python stand-in applies the rules above to a list of sources of values and shows the winner for each variable. It is a model written for teaching, but the order matches the list.

Python Stand-in: which value wins?

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 validation stand-in

The same logic used for condition can be tested in Python before you encode it in HCL.

Python Stand-in: validate variable values

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.

Sensitive variables

HCL
variable "db_password" {
  type      = string
  sensitive = true
}

Packer hides sensitive values in its terminal UI. This is a display feature, not encryption: the value still ends up wherever you use it (for example in a shell command run on the machine, in the debug log, or baked into the image). Data sources and sensitive values explains how to fetch secrets safely and keep them out of images.

Inspecting variables

Terminal
packer inspect .

lists each variable with its type, default and description. Good descriptions turn that output into documentation.

Naming and style

  • Use snake_case names that say what the value means: app_version, not v.
  • Group related settings in an object only when they travel together; otherwise keep flat variables.
  • Put all variables in variables.pkr.hcl (project layout).
  • Give every variable a description, and a default only when one is genuinely safe.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A variable block has no default and nothing sets it. What happens?

    Variables without defaults are required, and validate/build stop if no value is supplied.
  2. 2. Which value wins: default, PKR_VAR_x, an auto.pkrvars file or -var?

    The command line has the highest priority. The order from lowest to highest is default, environment, auto var files, then -var-file/-var in the order given.
  3. 3. What is can(regex(...)) used for in a validation condition?

    can() returns true if the expression evaluates without error, otherwise false.
  4. 4. Which name sets the variable region from the environment?

    Environment variables use the PKR_VAR_ prefix followed by the variable name.
  5. 5. Does sensitive = true encrypt the value inside the finished image?

    It is a display feature. If you write the value into the machine, it stays there.

Summary

  • Declare inputs with variable blocks (type, default, description, sensitive, validation); no default means required.
  • Types: string, number, bool, list, set, map, object, any; compatible values are converted.
  • validation blocks reject bad values before any machine is created.
  • Precedence, lowest to highest: default, PKR_VAR_*, *.auto.pkrvars.*, then -var-file and -var in command-line order.
  • sensitive hides values in output only; it does not protect them inside images.

Next: Locals and expressions