github.com/ferranbt/nomad@v0.9.3-0.20190607002617-85c449b7667c/website/source/docs/job-specification/template.html.md (about)

     1  ---
     2  layout: "docs"
     3  page_title: "template Stanza - Job Specification"
     4  sidebar_current: "docs-job-specification-template"
     5  description: |-
     6    The "template" block instantiates an instance of a template renderer. This
     7    creates a convenient way to ship configuration files that are populated from
     8    environment variables, Consul data, Vault secrets, or just general
     9    configurations within a Nomad task.
    10  ---
    11  
    12  # `template` Stanza
    13  
    14  <table class="table table-bordered table-striped">
    15    <tr>
    16      <th width="120">Placement</th>
    17      <td>
    18        <code>job -> group -> task -> **template**</code>
    19      </td>
    20    </tr>
    21  </table>
    22  
    23  The `template` block instantiates an instance of a template renderer. This
    24  creates a convenient way to ship configuration files that are populated from
    25  environment variables, Consul data, Vault secrets, or just general
    26  configurations within a Nomad task.
    27  
    28  ```hcl
    29  job "docs" {
    30    group "example" {
    31      task "server" {
    32        template {
    33          source        = "local/redis.conf.tpl"
    34          destination   = "local/redis.conf"
    35          change_mode   = "signal"
    36          change_signal = "SIGINT"
    37        }
    38      }
    39    }
    40  }
    41  ```
    42  
    43  Nomad utilizes a tool called [Consul Template][ct]. Since Nomad v0.5.3, the
    44  template can reference [Nomad's runtime environment variables][env]. Since Nomad
    45  v0.5.6, the template can reference [Node attributes and metadata][nodevars]. For
    46  a full list of the API template functions, please refer to the [Consul Template
    47  README][ct]. Since Nomad v0.6.0, templates can be read as environment variables.
    48  
    49  ## `template` Parameters
    50  
    51  - `change_mode` `(string: "restart")` - Specifies the behavior Nomad should take
    52    if the rendered template changes. Nomad will always write the new contents of
    53    the template to the specified destination. The possible values below describe
    54    Nomad's action after writing the template to disk.
    55  
    56    - `"noop"` - take no action (continue running the task)
    57    - `"restart"` - restart the task
    58    - `"signal"` - send a configurable signal to the task
    59  
    60  - `change_signal` `(string: "")` - Specifies the signal to send to the task as a
    61    string like `"SIGUSR1"` or `"SIGINT"`. This option is required if the
    62    `change_mode` is `signal`.
    63  
    64  - `data` `(string: "")` - Specifies the raw template to execute. One of `source`
    65    or `data` must be specified, but not both. This is useful for smaller
    66    templates, but we recommend using `source` for larger templates.
    67  
    68  - `destination` `(string: <required>)` - Specifies the location where the
    69    resulting template should be rendered, relative to the task directory.
    70  
    71  - `env` `(bool: false)` - Specifies the template should be read back in as
    72    environment variables for the task. ([See below](#environment-variables))
    73  
    74  - `left_delimiter` `(string: "{{")` - Specifies the left delimiter to use in the
    75    template. The default is "{{" for some templates, it may be easier to use a
    76    different delimiter that does not conflict with the output file itself.
    77  
    78  - `perms` `(string: "644")` - Specifies the rendered template's permissions.
    79    File permissions are given as octal of the Unix file permissions `rwxrwxrwx`.
    80  
    81  - `right_delimiter` `(string: "}}")` - Specifies the right delimiter to use in the
    82    template. The default is "}}" for some templates, it may be easier to use a
    83    different delimiter that does not conflict with the output file itself.
    84  
    85  - `source` `(string: "")` - Specifies the path to the template to be rendered.
    86    One of `source` or `data` must be specified, but not both. This source can
    87    optionally be fetched using an [`artifact`][artifact] resource. This template
    88    must exist on the machine prior to starting the task; it is not possible to
    89    reference a template inside of a Docker container, for example.
    90  
    91  - `splay` `(string: "5s")` - Specifies a random amount of time to wait between
    92    0 ms and the given splay value before invoking the change mode. This is
    93    specified using a label suffix like "30s" or "1h", and is often used to
    94    prevent a thundering herd problem where all task instances restart at the same
    95    time.
    96  
    97  -   `vault_grace` `(string: "15s")` - Specifies the grace period between lease
    98      renewal and secret re-acquisition. When renewing a secret, if the remaining
    99      lease is less than or equal to the configured grace, the template will request
   100      a new credential. This prevents Vault from revoking the secret at its
   101      expiration and the task having a stale secret.
   102  
   103      If the grace is set to a value that is higher than your default TTL or max
   104      TTL, the template will always read a new secret. **If secrets are being
   105      renewed constantly, decrease the `vault_grace`.**
   106  
   107      If the task defines several templates, the `vault_grace` will be set to the
   108      lowest value across all the templates.
   109  
   110  
   111  ## `template` Examples
   112  
   113  The following examples only show the `template` stanzas. Remember that the
   114  `template` stanza is only valid in the placements listed above.
   115  
   116  ### Inline Template
   117  
   118  This example uses an inline template to render a file to disk. This file watches
   119  various keys in Consul for changes:
   120  
   121  ```hcl
   122  template {
   123    data        = "---\nkey: {{ key \"service/my-key\" }}"
   124    destination = "local/file.yml"
   125  }
   126  ```
   127  
   128  It is also possible to use heredocs for multi-line templates, like:
   129  
   130  ```hcl
   131  template {
   132    data = <<EOH
   133    ---
   134      bind_port:   {{ env "NOMAD_PORT_db" }}
   135      scratch_dir: {{ env "NOMAD_TASK_DIR" }}
   136      node_id:     {{ env "node.unique.id" }}
   137      service_key: {{ key "service/my-key" }}
   138    EOH
   139  
   140    destination = "local/file.yml"
   141  }
   142  ```
   143  
   144  ### Remote Template
   145  
   146  This example uses an [`artifact`][artifact] stanza to download an input template
   147  before passing it to the template engine:
   148  
   149  ```hcl
   150  artifact {
   151    source      = "https://example.com/file.yml.tpl"
   152    destination = "local/file.yml.tpl"
   153  }
   154  
   155  template {
   156    source      = "local/file.yml.tpl"
   157    destination = "local/file.yml"
   158  }
   159  ```
   160  
   161  ### Node Variables
   162  
   163  As of Nomad v0.5.6 it is possible to access the Node's attributes and metadata.
   164  
   165  ```hcl
   166  template {
   167    data = <<EOH
   168    ---
   169      node_dc:    {{ env "node.datacenter" }}
   170      node_cores: {{ env "attr.cpu.numcores" }}
   171      meta_key:   {{ env "meta.node_meta_key" }}
   172    EOH
   173  
   174    destination = "local/file.yml"
   175  }
   176  ```
   177  
   178  ### Environment Variables
   179  
   180  Since v0.6.0 templates may be used to create environment variables for tasks.
   181  Env templates work exactly like other templates except once the templates are
   182  written, they are parsed as `KEY=value` pairs. Those key value pairs are
   183  included in the task's environment.
   184  
   185  For example the following template stanza:
   186  
   187  ```hcl
   188  template {
   189    data = <<EOH
   190  # Lines starting with a # are ignored
   191  
   192  # Empty lines are also ignored
   193  LOG_LEVEL="{{key "service/geo-api/log-verbosity"}}"
   194  API_KEY="{{with secret "secret/geo-api-key"}}{{.Data.value}}{{end}}"
   195  EOH
   196  
   197    destination = "secrets/file.env"
   198    env         = true
   199  }
   200  ```
   201  
   202  The task's environment would then have environment variables like the
   203  following:
   204  
   205  ```
   206  LOG_LEVEL=DEBUG
   207  API_KEY=12345678-1234-1234-1234-1234-123456789abc
   208  ```
   209  
   210  This allows [12factor app](https://12factor.net/config) style environment
   211  variable based configuration while keeping all of the familiar features and
   212  semantics of Nomad templates.
   213  
   214  Secrets or certificates may contain a wide variety of characters such as
   215  newlines, quotes, and backslashes which may be difficult to quote or escape
   216  properly.
   217  
   218  Whenever a templated variable may include special characters, use the `toJSON`
   219  function to ensure special characters are properly parsed by Nomad:
   220  
   221  ```
   222  CERT_PEM={{ file "path/to/cert.pem" | toJSON }}
   223  ```
   224  
   225  The parser will read the JSON string, so the `$CERT_PEM` environment variable
   226  will be identical to the contents of the file.
   227  
   228  Likewise when evaluating a password that may contain quotes or `#`, use the
   229  `toJSON` function to ensure Nomad passes the password to task unchanged:
   230  
   231  ```
   232  # Passwords may contain any character including special characters like:
   233  #   \"'#
   234  # Use toJSON to ensure Nomad passes them to the environment unchanged.
   235  {{ with secret "secrets/data/application/backend" }}
   236  DB_PASSWD={{ .Data.data.DB_PASSWD | toJSON }}
   237  {{ end }}
   238  ```
   239  
   240  For more details see [go-envparser's
   241  README](https://github.com/hashicorp/go-envparse#readme).
   242  
   243  ## Vault Integration
   244  
   245  ### PKI Certificate
   246  
   247  This example acquires a PKI certificate from Vault in PEM format and stores it into your application's secret directory.
   248  
   249  ```hcl
   250  template {
   251    data = <<EOH
   252  {{ with secret "pki/issue/foo" "common_name=foo.service.consul" "ip_sans=127.0.0.1" "format=pem" }}
   253  {{ .Data.certificate }}
   254  {{ .Data.issuing_ca }}
   255  {{ .Data.private_key }}{{ end }}
   256  EOH
   257    destination   = "${NOMAD_SECRETS_DIR}/bundle.pem"
   258    change_mode   = "restart"
   259  }
   260  ```
   261  
   262  Most users should set `generate_lease=true` on the `pki/issue/foo` role in Vault's
   263  PKI backend. If this value is not set, the template stanza will frequently render a new
   264  certificate, approximately every minute, which is probably not what you want.
   265  
   266  ### Vault KV API v1
   267  
   268  Under Vault KV API v1, paths start with `secret/`, and the response returns the
   269  raw key/value data. This secret was set using
   270  `vault kv put secret/aws/s3 aws_access_key_id=somekeyid`.
   271  
   272  ```hcl
   273    template {
   274      data = <<EOF
   275        AWS_ACCESS_KEY_ID = "{{with secret "secret/aws/s3"}}{{.Data.aws_access_key_id}}{{end}}"
   276      EOF
   277    }
   278  ```
   279  
   280  ### Vault KV API v2
   281  
   282  Under Vault KV API v2, paths start with `secret/data/`, and the response returns
   283  metadata in addition to key/value data. This secret was set using
   284  `vault kv put secret/aws/s3 aws_access_key_id=somekeyid`.
   285  
   286  ```hcl
   287    template {
   288      data = <<EOF
   289        AWS_ACCESS_KEY_ID = "{{with secret "secret/data/aws/s3"}}{{.Data.data.aws_access_key_id}}{{end}}"
   290      EOF
   291    }
   292  ```
   293  
   294  Notice the addition of `data` in both the path and the field accessor string.
   295  Additionally, when using the Vault v2 API, the Vault policies applied to your
   296  Nomad jobs will need to grant permissions to `read` under `secret/data/...`
   297  rather than `secret/...`.
   298  
   299  ## Client Configuration
   300  
   301  The `template` block has the following [client configuration
   302  options](/docs/configuration/client.html#options):
   303  
   304  * `template.allow_host_source` - Allows templates to specify their source
   305    template as an absolute path referencing host directories. Defaults to `true`.
   306  
   307  [ct]: https://github.com/hashicorp/consul-template "Consul Template by HashiCorp"
   308  [artifact]: /docs/job-specification/artifact.html "Nomad artifact Job Specification"
   309  [env]: /docs/runtime/environment.html "Nomad Runtime Environment"
   310  [nodevars]: /docs/runtime/interpolation.html#interpreted_node_vars "Nomad Node Variables"