github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/website/content/docs/job-specification/hcl2/variables.mdx (about)

     1  ---
     2  layout: docs
     3  page_title: Input Variables - HCL Configuration Language
     4  description: |-
     5    Input variables are parameters for Nomad jobs.
     6    This page covers configuration syntax for variables.
     7  ---
     8  
     9  # Input Variables
    10  
    11  Input variables serve as parameters for a Nomad job, allowing aspects of the
    12  job to be customized without altering the job's own source code.
    13  
    14  When you declare variables in the same file as the job specification, you
    15  can set their values using CLI options and environment variables.
    16  
    17  -> **Note:** For brevity, input variables are often referred to as just
    18  "variables" or "Nomad variables" when it is clear from context what sort of
    19  variable is being discussed. Other kinds of variables in Nomad include
    20  _environment variables_ (set by the shell where Nomad runs) and _expression
    21  variables_ (used to indirectly represent a value in an
    22  [expression](/docs/job-specification/hcl2/expressions)).
    23  
    24  ## Declaring an Input Variable
    25  
    26  Each input variable accepted by a job must be declared using a `variable`
    27  block :
    28  
    29  ```hcl
    30  variable "image_id" {
    31    type = string
    32  }
    33  
    34  variable "availability_zone_names" {
    35    type    = list(string)
    36    default = ["us-west-1a"]
    37  }
    38  
    39  variable "docker_ports" {
    40    type = list(object({
    41      internal = number
    42      external = number
    43      protocol = string
    44    }))
    45    default = [
    46      {
    47        internal = 8300
    48        external = 8300
    49        protocol = "tcp"
    50      }
    51    ]
    52  }
    53  ```
    54  
    55  Or a less precise variables block:
    56  
    57  ```hcl
    58  variables {
    59    foo       = "value"
    60    my_secret = "foo"
    61  }
    62  ```
    63  
    64  The label after the `variable` keyword or a label of a `variables` block is a
    65  name for the variable, which must be unique among all variables in the same
    66  job. This name is used to assign a value to the variable from outside and to
    67  reference the variable's value from within the job.
    68  
    69  The `variable` block can optionally include a `type` argument to specify what
    70  value types are accepted for the variable, as described in the following
    71  section.
    72  
    73  The `variable` declaration can also include a `default` argument. If present,
    74  the variable is considered to be _optional_ and the default value will be used
    75  if no value is set when calling the job or running Nomad. The `default`
    76  argument requires a literal value and cannot reference other objects in the
    77  configuration.
    78  
    79  ## Using Input Variable Values
    80  
    81  Within the job that declared a variable, its value can be accessed from within
    82  [expressions](/docs/job-specification/hcl2/expressions) as `var.<NAME>`, where
    83  `<NAME>` matches the label given in the declaration block:
    84  
    85  ```hcl
    86  config {
    87    image = var.task_image
    88    label = var.task_labels
    89  }
    90  ```
    91  
    92  The value assigned to a variable can be accessed only from expressions within
    93  the folder where it was declared. Note that a block label (such as the job ID
    94  or task group name) is not an expression and so can't be interpolated with a
    95  variable or local.
    96  
    97  ## Type Constraints
    98  
    99  The `type` argument in a `variable` block allows you to restrict the [type of
   100  value](/docs/job-specification/hcl2/expressions#types-and-values) that will be
   101  accepted as the value for a variable. If no type constraint is set then a
   102  value of any type is accepted.
   103  
   104  While type constraints are optional, we recommend specifying them; they serve
   105  as easy reminders for users of the job, and allow Nomad to return a helpful
   106  error message if the wrong type is used.
   107  
   108  Type constraints are created from a mixture of type keywords and type
   109  constructors. The supported type keywords are:
   110  
   111  - `string`
   112  - `number`
   113  - `bool`
   114  
   115  The type constructors allow you to specify complex types such as collections:
   116  
   117  - `list(<TYPE>)`
   118  - `set(<TYPE>)`
   119  - `map(<TYPE>)`
   120  - `object({<ATTR NAME> = <TYPE>, ... })`
   121  - `tuple([<TYPE>, ...])`
   122  
   123  The keyword `any` may be used to indicate that any type is acceptable. For more
   124  information on the meaning and behavior of these different types, as well as
   125  detailed information about automatic conversion of complex types, see [Type
   126  Constraints](https://www.terraform.io/language/expressions/type-constraints).
   127  
   128  If both the `type` and `default` arguments are specified, the given default
   129  value must be convertible to the specified type.
   130  
   131  If only `default` is specified, the type of the default value will be used.
   132  
   133  When the `type` and `default` are both _not_ specified and you try to set a
   134  variable [from env vars](#environment-variables) or [from the command
   135  line](#variables-on-the-command-line), the variable will always be interpreted
   136  as a string.
   137  
   138  ## Input Variable Documentation
   139  
   140  Because the input variables of a job are part of its user interface, you can
   141  briefly describe the purpose of each variable using the optional `description`
   142  argument:
   143  
   144  ```hcl
   145  variable "image_id" {
   146    type        = string
   147    description = "The docker image used for task."
   148  }
   149  ```
   150  
   151  The description should concisely explain the purpose of the variable and what
   152  kind of value is expected. This description string might be included in
   153  documentation about the job, and so it should be written from the perspective
   154  of the user of the job rather than its maintainer. For commentary for job
   155  maintainers, use comments.
   156  
   157  ## Input Variable Custom Validation Rules
   158  
   159  Input variables support specifying arbitrary custom validation rules for a particular
   160  variable using a `validation` block nested within the corresponding `variable` block:
   161  
   162  ```hcl
   163  variable "image_id" {
   164    type        = string
   165    description = "The id of the machine image (AMI) to use for the server."
   166  
   167    validation {
   168      condition     = substr(var.image_id, 0, 4) == "ami-"
   169      error_message = "The image_id value must be a valid AMI id, starting with \"ami-\"."
   170    }
   171  }
   172  ```
   173  
   174  The condition argument is an expression that must use the value of the variable to
   175  return true if the value is valid, or false if it is invalid. The expression can
   176  refer only to the variable that the condition applies to, and _must_ not produce errors.
   177  
   178  If condition evaluates to false, Nomad will produce an error message that includes
   179  the sentences given in `error_message`. The error message string should be at least
   180  one full sentence explaining the constraint that failed, starting with an uppercase
   181  letter ( if the alphabet permits it ) and ending with a period or question mark.
   182  
   183  Multiple validation blocks can be declared in which case error messages will be
   184  returned for all failed conditions.
   185  
   186  ## Assigning Values to job Variables
   187  
   188  Once a variable is declared in your configuration, you can set it:
   189  
   190  - Individually, with the `-var foo=bar` command line option.
   191  - In variable definitions files specified on the command line (with `-var-file=input.vars`).
   192  - As environment variables, for example: `NOMAD_VAR_foo=bar`
   193  
   194  The following sections describe these options in more detail.
   195  
   196  ### Variables on the Command Line
   197  
   198  To specify individual variables on the command line, use the `-var` option when
   199  running the `nomad job run` command:
   200  
   201  ```shell-session
   202  $ nomad job run -var="image_id=nginx:1.19" example.nomad
   203  ```
   204  
   205  The `-var` option can be used any number of times in a single command.
   206  
   207  If you plan to assign variables via the command line, we strongly recommend that
   208  you at least set a default type instead of using empty blocks; this helps the
   209  HCL parser understand what is being set. Otherwise, the interpreter will assume
   210  that any variable set on the command line is a string.
   211  
   212  ### Variable Definitions Files
   213  
   214  To set lots of variables, it is more convenient to specify their values in a
   215  _variable definitions file_ and then specify that file on the command line with
   216  `-var-file`:
   217  
   218  ```shell-session
   219  $ nomad job run -var-file="testing.vars" example.nomad
   220  ```
   221  
   222  A variable definitions file uses the same HCL basic syntax, but consists only
   223  of variable name assignments:
   224  
   225  ```hcl
   226  image_id = "nginx:1.19"
   227  labels = [
   228    "testing",
   229    "internal",
   230  ]
   231  ```
   232  
   233  Alternatively, the files can be JSON objects, with the root object properties
   234  corresponding to variable names:
   235  
   236  ```json
   237  {
   238    "image_id": "nginx:1.19",
   239    "labels": ["testing", "internal"]
   240  }
   241  ```
   242  
   243  ### Environment Variables
   244  
   245  As a fallback for the other ways of defining variables, Nomad searches the
   246  environment of its own process for environment variables named `NOMAD_VAR_`
   247  followed by the name of a declared variable.
   248  
   249  This can be useful when running Nomad in automation, or when running a
   250  sequence of Nomad commands in succession with the same variables. For example,
   251  at a `bash` prompt on a Unix system:
   252  
   253  ```shell-session
   254  $ export NOMAD_VAR_image_id=nginx:1.19
   255  $ nomad job run example.nomad
   256  ...
   257  ```
   258  
   259  On operating systems where environment variable names are case-sensitive,
   260  Nomad matches the variable name exactly as given in configuration, and so the
   261  required environment variable name will usually have a mix of upper and lower
   262  case letters as in the above example.
   263  
   264  ### Complex-typed Values
   265  
   266  When variable values are provided in a variable definitions file, Nomad's
   267  [usual syntax](/docs/job-specification/hcl2/expressions) can be used to assign
   268  complex-typed values, like lists and maps.
   269  
   270  Some special rules apply to the `-var` command line option and to environment
   271  variables. For convenience, Nomad defaults to interpreting `-var` and
   272  environment variable values as literal strings, which do not need to be quoted:
   273  
   274  ```shell-session
   275  $ export NOMAD_VAR_image_id=nginx:1.19
   276  ```
   277  
   278  However, if an input variable uses a [type constraint](#type-constraints) to
   279  require a complex value (list, set, map, object, or tuple), Nomad will instead
   280  attempt to parse its value using the same syntax used within variable
   281  definitions files, which requires careful attention to the string escaping
   282  rules in your shell:
   283  
   284  ```shell-session
   285  $ export NOMAD_VAR_availability_zone_names='["us-west-1b","us-west-1d"]'
   286  ```
   287  
   288  For readability, and to avoid the need to worry about shell escaping, we
   289  recommend always setting complex variable values via variable definitions
   290  files.
   291  
   292  ### Variable Definition Precedence
   293  
   294  The above mechanisms for setting variables can be used together in any
   295  combination.
   296  
   297  Nomad loads variables in the following order, with later sources taking
   298  precedence over earlier ones:
   299  
   300  - Environment variables (lowest priority)
   301  - Any `-var` and `-var-file` options on the command line, in the order they are
   302    provided. (highest priority)
   303  
   304  If the same variable is assigned multiple values using different mechanisms,
   305  Nomad uses the _last_ value it finds, overriding any previous values. Note
   306  that the same variable cannot be assigned multiple values within a single source.
   307  
   308  ~> **Important:** Variables with map and object values behave the same way as
   309  other variables: the last value found overrides the previous values.
   310  
   311  ## A variable value must be known:
   312  
   313  Take the following variable for example:
   314  
   315  ```hcl
   316  variable "foo" {
   317    type = string
   318  }
   319  ```
   320  
   321  Here `foo` must have a known value but you can default it to `null` to make
   322  this behavior optional :
   323  
   324  |                                 |          no default          | `default = null` | `default = "xy"` |
   325  | :-----------------------------: | :--------------------------: | :--------------: | :--------------: |
   326  |           foo unused            | error, "foo needs to be set" |        -         |        -         |
   327  |             var.foo             | error, "foo needs to be set" |       null       |        xy        |
   328  | `NOMAD_VAR_foo=yz`<br />var.foo |              yz              |        yz        |        yz        |
   329  |   `-var foo=yz`<br />var.foo    |              yz              |        yz        |        yz        |