»The variable block

The variable block, also called the input-variable block, defines variables within your Packer configuration. An input-variable cannot be used in another input variable: we recommend using locals for that instead.

# variables.pkr.hcl
variable "foo" {
    type = string
    default = "the default value of the `foo` variable"
    description = "description of the `foo` variable"

»Default value

If a default value is set, the variable is optional. Otherwise, the variable must be set.

»Assigning Values to build Variables

Once a variable is declared in your configuration, you can set it:

  • Individually, with the -var foo=bar command line option.
  • In variable definitions (.pkrvars.hcl) files, either specified on the command line or automatically loaded.
  • As environment variables, for example: PKR_VAR_foo=bar

Example of a variable assignment from a file:

# foo.pkrvars.hcl
foo = "value"

»A variable value must be known:

Take the following variable for example:

variable "foo" {
  type = string

Here foo must have a known value but you can default it to null to make this behavior optional :

no defaultdefault = nulldefault = "xy"
foo unusederror, "foo needs to be set"--
var.fooerror, "foo needs to be set"null¹xy
-var foo=yz

1: Null is a valid value. Packer will only error when the receiving field needs a value, example:

variable "example" {
  type = string
  default = null

source "example" "foo" {
  arg = var.example

In the above case, as long as "arg" is optional for an "example" source, there is no error and arg won’t be set.

»More on variables