»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"
    sensitive   = false
    # When a variable is sensitive all string-values from that variable will be
    # obfuscated from Packer's output.
}

»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 and .auto.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
PKR_VAR_foo=yz
var.foo
yzyzyz
-var foo=yz
var.foo
yzyzyz

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.

»A variable can be sensitive

When a variable is sensitive all string-values from that variable will be obfuscated from Packer's output :

# var-foo.pkr.hcl
variable "foo" {
    sensitive = true
    default   = {
        key = "SECR3TP4SSW0RD"
    }
}
$ packer inspect var-foo.pkr.hcl
Packer Inspect: HCL2 mode

> input-variables:
var.foo: "{\n  \"key\" = \"<sensitive>\"\n }"
...

»More on variables