»The variable block

Note: This page is about HCL2 Packer templates. HCL2 templates were first introduced as a beta feature into Packer version 1.5. As of v1.7, HCL2 support is no longer in beta, and is the preferred way to write Packer configuration. For the old-style stable configuration language see template docs. As of v1.6.2, you can convert your legacy JSON template into an HCL2 config file using the hcl2_upgrade command.

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.

»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

»Custom Validation Rules

In addition to Type Constraints, you can specify arbitrary custom validation rules for a particular variable using one or more validation block nested within the corresponding variable block:

The condition argument is an expression that must use the value of the variable to return true if the value is valid or false if it is invalid. The expression can refer only to the variable that the condition applies to, and must not produce errors.

If the failure of an expression is the basis of the validation decision, use the can function to detect such errors. For example:

If condition evaluates to false, an error message including the sentences given in error_message will be produced. The error message string should be at least one full sentence explaining the constraint that failed, using a sentence structure similar to the above examples.

Validation also works with more complex cases:

Example of a variable assignment from a file:

»A variable value must be known:

Take the following variable for example:

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

no default default = null default = "xy"
foo unused error, "foo needs to be set" - -
var.foo error, "foo needs to be set" null¹ xy
PKR_VAR_foo=yz
var.foo
yz yz yz
-var foo=yz
var.foo
yz yz yz

1: Null is a valid value. Packer will only error when the receiving field needs a value, 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 :

»More on variables

  • Read the full variables description for a more thorough read.
  • Read the variables guide for more examples.