github.com/hashicorp/packer@v1.14.3/website/content/docs/templates/hcl_templates/variables.mdx (about)

     1  ---
     2  page_title: Input variables reference
     3  description: |-
     4    Input variables are parameters for Packer modules.
     5    Learn how to use the input variable syntax for Packer templates written in HCL.
     6  ---
     7  
     8  # Input Variables
     9  
    10  This topic provides reference information about input variables in Packer templates. Refer to [Local Variables](/packer/docs/templates/hcl_templates/locals) for information about using local variables in Packer. 
    11  
    12  ## Introduction
    13  
    14  Input variables, sometimes referred to as variables or Packer variables, are the parameters for a Packer build. Input variables let you customize aspects of a build without altering the build's own source code. Some input variables have default values that you can override using command line options, environment variables, or variable definitions files. You cannot change the value of an input variable after the initial override.
    15  
    16  Refer to [Input Variables and local variables](/packer/guides/hcl/variables) for additional information.
    17  
    18  ## Declaring an Input Variable
    19  
    20  Each input variable accepted by a build must be declared using a `variable`
    21  block :
    22  
    23  ```hcl
    24  variable "image_id" {
    25    type = string
    26  }
    27  
    28  variable "availability_zone_names" {
    29    type    = list(string)
    30    default = ["us-west-1a"]
    31  }
    32  
    33  variable "docker_ports" {
    34    type = list(object({
    35      internal = number
    36      external = number
    37      protocol = string
    38    }))
    39    default = [
    40      {
    41        internal = 8300
    42        external = 8300
    43        protocol = "tcp"
    44      }
    45    ]
    46  }
    47  ```
    48  
    49  Or a less precise variables block:
    50  
    51  ```hcl
    52  variables {
    53     foo = "value"
    54     my_secret = "foo"
    55  }
    56  ```
    57  
    58  The label after the `variable` keyword or a label of a `variables` block is a
    59  name for the variable, which must be unique among all variables in the same
    60  build. This name is used to assign a value to the variable from outside and to
    61  reference the variable's value from within the build.
    62  
    63  
    64  ## Arguments
    65  
    66  Packer defines the following arguments for variable declarations:
    67  
    68  * [`default`][inpage-default] - A default value which then makes the variable optional.
    69  * [`type`][inpage-type] - This argument specifies what value types are accepted for the variable.
    70  * [`description`][inpage-description] - This specifies the input variable's documentation.
    71  * [`validation`][inpage-validation] - A block to define validation rules, usually in addition to type constraints.
    72  * [`sensitive`][inpage-sensitive] -  This causes string-values from that variable to be obfuscated from Packer's output.
    73  
    74  
    75  
    76  ### Default values
    77  
    78  [inpage-default]: #default-values
    79  
    80  The variable declaration can also include a `default` argument. If present,
    81  the variable is considered to be _optional_ and the default value will be used
    82  if no value is set when running Packer. The `default`
    83  argument requires a literal value and cannot reference other objects in the
    84  configuration.
    85  
    86  
    87  ### Type Constraints
    88  [inpage-type]: #type-constraints
    89  
    90  The `type` argument in a `variable` block allows you to restrict the [type of
    91  value](/packer/docs/templates/hcl_templates/expressions#types-and-values) that will be accepted as the value
    92  for a variable. If no type constraint is set then a value of any type is
    93  accepted.
    94  
    95  While type constraints are optional, we recommend specifying them; they serve
    96  as easy reminders for users of the build, and allow Packer to return a helpful
    97  error message if the wrong type is used.
    98  
    99  Type constraints are created from a mixture of type keywords and type
   100  constructors. The supported type keywords are:
   101  
   102  - `string`
   103  - `number`
   104  - `bool`
   105  
   106  The type constructors allow you to specify complex types such as collections:
   107  
   108  - `list(<TYPE>)`
   109  - `set(<TYPE>)`
   110  - `map(<TYPE>)`
   111  - `object({<ATTR NAME> = <TYPE>, ... })`
   112  - `tuple([<TYPE>, ...])`
   113  
   114  The keyword `any` may be used to indicate that any type is acceptable. For more
   115  information on the meaning and behavior of these different types, as well as
   116  detailed information about automatic conversion of complex types, see [Type
   117  Constraints](/terraform/docs/configuration/types).
   118  
   119  If both the `type` and `default` arguments are specified, the given default
   120  value must be convertible to the specified type.
   121  
   122  If only `default` is specified, the type of the default value will be used.
   123  
   124  When the `type` and `default` are both _not_ specified and you try to set a
   125  variable [from env vars](#environment-variables) or [from the command
   126  line](#variables-on-the-command-line), the variable will always be interpreted
   127  as a string.
   128  
   129  ### Input Variable Documentation
   130  
   131  [inpage-description]: #input-variable-documentation
   132  
   133  Because the input variables of a build are part of its user interface, you can
   134  briefly describe the purpose of each variable using the optional `description`
   135  argument:
   136  
   137  ```hcl
   138  variable "image_id" {
   139    type        = string
   140    description = "The ID of the machine image (AMI) to use for the server."
   141  }
   142  ```
   143  
   144  The description should concisely explain the purpose of the variable and what
   145  kind of value is expected. This description string might be included in
   146  documentation about the build, and so it should be written from the perspective
   147  of the user of the build rather than its maintainer. For commentary for build
   148  maintainers, use comments.
   149  
   150  `@include 'from-1.5/variables/custom-validation.mdx'`
   151  
   152  `@include 'from-1.5/variables/sensitive.mdx'`
   153  
   154  
   155  ## Using Input Variable Values
   156  
   157  Within the build that declared a variable, its value can be accessed from
   158  within [expressions](/packer/docs/templates/hcl_templates/expressions) as `var.<NAME>`, where `<NAME>`
   159  matches the label given in the declaration block:
   160  
   161  ```hcl
   162  source "googlecompute" "debian"  {
   163      zone = var.gcp_zone
   164      tags = var.gcp_debian_tags
   165  }
   166  ```
   167  
   168  The value assigned to a variable can be accessed only from expressions within
   169  the folder where it was declared.
   170  
   171  
   172  `@include 'from-1.5/variables/assignment.mdx'`
   173  
   174  The following sections describe these options in more detail.
   175  
   176  ### Variables on the Command Line
   177  
   178  To specify individual variables on the command line, use the `-var` option when
   179  running the `packer build` command:
   180  
   181  ```shell-session
   182  $ packer build -var="image_id=ami-abc123"
   183  $ packer build -var='image_id_list=["ami-abc123","ami-def456"]'
   184  $ packer build -var='image_id_map={"us-east-1":"ami-abc123","us-east-2":"ami-def456"}'
   185  ```
   186  
   187  The `-var` option can be used any number of times in a single command.
   188  
   189  If you plan to assign variables via the command line, we strongly recommend that
   190  you at least set a default type instead of using empty blocks; this helps the
   191  HCL parser understand what is being set. Otherwise, the interpreter will assume
   192  that any variable set on the command line is a string.
   193  
   194  ### Standard Variable Definitions Files
   195  
   196  To set lots of variables, it is more convenient to specify their values in a
   197  _variable definitions file_ with a filename ending in either `.pkrvars.hcl` or
   198  `.pkrvars.json` and then specify that file on the command line with
   199  `-var-file`:
   200  
   201  ```shell-session
   202  $ packer build -var-file="testing.pkrvars.hcl"
   203  ```
   204  
   205  A variable definitions file uses the same basic syntax as Packer language
   206  files, but consists only of variable name and its assigned values:
   207  
   208  ```hcl
   209  image_id = "ami-abc123"
   210  availability_zone_names = [
   211    "us-east-1a",
   212    "us-west-1c",
   213  ]
   214  ```
   215  
   216  ~> **Important**: Unlike legacy JSON templates the input variables within a variable definitions file must be declared 
   217  via a variables block within a standard HCL2 template file `*.pkr.hcl` before it can be assigned a value. 
   218  Failure to do so will result in an unknown variable error during Packer's runtime.
   219  
   220  ### Auto-loaded Variable Definitions Files
   221  
   222  Packer also has the ability automatically load one or more variable definitions files if they
   223  are present:
   224  
   225  - Any files with names ending in `.auto.pkrvars.hcl` or `.auto.pkrvars.json`.
   226  
   227  Files whose names end with `.json` are parsed as JSON objects instead of HCL,
   228  with the root object properties corresponding to variable names:
   229  
   230  ```json
   231  {
   232    "image_id": "ami-abc123",
   233    "availability_zone_names": ["us-west-1a", "us-west-1c"]
   234  }
   235  ```
   236  
   237  ~> **Important**: Unlike legacy JSON templates the input variables within a variable definitions file must be declared 
   238  via a variables block within a standard HCL2 template file `*.pkr.hcl` before it can be assigned a value. 
   239  Failure to do so will result in an unknown variable error during Packer's runtime.
   240  
   241  
   242  ### Environment Variables
   243  
   244  As a fallback for the other ways of defining variables, Packer searches the
   245  environment of its own process for environment variables named `PKR_VAR_`
   246  followed by the name of a declared variable.
   247  
   248  This can be useful when running Packer in automation, or when running a
   249  sequence of Packer commands in succession with the same variables. For example,
   250  at a `bash` prompt on a Unix system:
   251  
   252  ```shell-session
   253  $ export PKR_VAR_image_id=ami-abc123
   254  $ packer build gcp/debian/
   255  ...
   256  ```
   257  
   258  On operating systems where environment variable names are case-sensitive,
   259  Packer matches the variable name exactly as given in configuration, and so the
   260  required environment variable name will usually have a mix of upper and lower
   261  case letters as in the above example.
   262  
   263  ### Complex-typed Values
   264  
   265  When variable values are provided in a variable definitions file, Packer's
   266  [usual syntax](/packer/docs/templates/hcl_templates/expressions) can be used to assign
   267  complex-typed values, like lists and maps.
   268  
   269  Some special rules apply to the `-var` command line option and to environment
   270  variables. For convenience, Packer defaults to interpreting `-var` and
   271  environment variable values as literal strings, which do not need to be quoted:
   272  
   273  ```shell-session
   274  $ export PKR_VAR_image_id=ami-abc123
   275  ```
   276  
   277  However, if a build variable uses a [type constraint](#type-constraints) to
   278  require a complex value (list, set, map, object, or tuple), Packer will instead
   279  attempt to parse its value using the same syntax used within variable
   280  definitions files, which requires careful attention to the string escaping
   281  rules in your shell:
   282  
   283  ```shell-session
   284  $ export PKR_VAR_availability_zone_names='["us-west-1b","us-west-1d"]'
   285  ```
   286  
   287  For readability, and to avoid the need to worry about shell escaping, we
   288  recommend always setting complex variable values via variable definitions
   289  files.
   290  
   291  ### Variable Definition Precedence
   292  
   293  The above mechanisms for setting variables can be used together in any
   294  combination.
   295  
   296  Packer loads variables in the following order, with later sources taking
   297  precedence over earlier ones:
   298  
   299  - Environment variables (lowest priority)
   300  - Any `*.auto.pkrvars.hcl` or `*.auto.pkrvars.json` files, processed in lexical
   301    order of their filenames.
   302  - Any `-var` and `-var-file` options on the command line, in the order they are
   303    provided. (highest priority)
   304  
   305  If the same variable is assigned multiple values using different mechanisms,
   306  Packer uses the _last_ value it finds, overriding any previous values. Note
   307  that the same variable cannot be assigned multiple values within a single source.
   308  
   309  ~> **Important:** Variables with map and object values behave the same way as
   310  other variables: the last value found overrides the previous values.
   311  
   312  `@include 'from-1.5/variables/must-be-set.mdx'`
   313  
   314  ### Setting an unknown variable will not always fail:
   315  
   316  |             Usage              |     packer validate     | any other packer command  |
   317  | :----------------------------: | :---------------------: | :-----------------------: |
   318  | `bar=yz` in .pkrvars.hcl file. | error, "bar undeclared" | warning, "bar undeclared" |
   319  |   `var.bar` in .pkr.hcl file   | error, "bar undeclared" |  error, "bar undeclared"  |
   320  |     `-var bar=yz` argument     | error, "bar undeclared" |  error, "bar undeclared"  |
   321  |    `export PKR_VAR_bar=yz`     |            -            |             -             |
   322