Skip to main content

Packer Variables

https://developer.hashicorp.com/packer/docs/templates/hcl_templates/variables

Variables in Packer are practically the same as Terraform.

A variable block can have the following arguments

  • default: Default value if not defined, it is optional.

  • type: every variable must be of type string, number or bool

    • string
    • number
    • bool
    • But it can also be a set of them
    list(`<TYPE>`)
    set(<`TYPE>`)
    map(`<TYPE>`)
    object({`<ATTR NAME>` = `<TYPE>`, ... })
    tuple([`<TYPE>`, ...])
  • description - Variable documentation, it is good practice to use, but not mandatory.

  • validation - Block that validates whether the variable value can be used or not. Not mandatory.

  • sensitive - If the variable value should not be displayed in the console, set to true. The default is false and it is not mandatory.

Let's look at this example. The variable name is in quotes, lowercase and _ should be used instead of - if the name is compound.

variable "environment" {
type = string
description = "Environment name"
}
variable "instance_type" {
type = string
description = "Instance that will be used for processing configurations"
default = "t3.medium"
}

Now imagine that environment can only be develop, staging or production, what to do? In this case we are putting a conditional with an error if the value develop, staging or production is not established.

variable "environment" {
type = string
description = "Environment where the image will be used"
validation {
condition = contains(["develop", "staging", "production"], var.environment)
error_message = "Invalid input, options: \"development\", \"staging\" or \"production\"."
}
}

In this we can observe that contains is a function that takes as input a list of possible words and will return true if any of them is in the var.environment variable that is passed.

Functions are very useful and can be found in the official documentation. I will make a list of the most used functions further ahead.

Check now what we have in project/variables.pkr.hcl

In addition we have what we will use as input in these variables in project/vars

Note that I can redefine a variable value that already has a default value.

The advantage of working with a file to inject values into variables is that if I want to have 10 different files of these I can just call the build function passing what I want.

I can have an input for production, one for develop and another for staging.

Extra

Path Variables

  • path.cwd: the directory from which Packer was started.
  • path.root: the directory of the input HCL file or the input folder.

Some variables are special and existing that can be referenced in the build in relation to the source. This will be explained in build.