github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/website/content/docs/job-specification/hcl2/variables.mdx (about)

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