Access Node Meta and Attrs in template

This PR allows accessing the Node's attributes and metadata as in a
template.

```
template {
    data = "{{ env \"attr.unique.network.ip-address\" }}"
    destination = "local/out"
}
```
This commit is contained in:
Alex Dadgar 2017-03-27 14:58:04 -07:00
parent 68650f78b9
commit 23562d77c9
3 changed files with 37 additions and 4 deletions

View file

@ -350,7 +350,7 @@ func templateRunner(tmpls []*structs.Template, config *config.Config,
}
// Set Nomad's environment variables
runner.Env = taskEnv.Build().EnvMap()
runner.Env = taskEnv.Build().EnvMapAll()
// Build the lookup
idMap := runner.TemplateConfigMapping()

View file

@ -287,6 +287,20 @@ func (t *TaskEnvironment) EnvMap() map[string]string {
return m
}
// EnvMap returns the environment variables that will be set as well as node
// meta/attrs in the map. This is appropriate for interpolation.
func (t *TaskEnvironment) EnvMapAll() map[string]string {
m := make(map[string]string, len(t.TaskEnv))
for k, v := range t.TaskEnv {
m[k] = v
}
for k, v := range t.NodeValues {
m[k] = v
}
return m
}
// Builder methods to build the TaskEnvironment
func (t *TaskEnvironment) SetAllocDir(dir string) *TaskEnvironment {
t.AllocDir = dir

View file

@ -41,8 +41,9 @@ job "docs" {
```
Nomad utilizes a tool called [Consul Template][ct]. Since Nomad v0.5.3, the
template can reference [Nomad's runtime environment variables][env]. For a full
list of the API template functions, please refer to the [Consul Template
template can reference [Nomad's runtime environment variables][env]. Since Nomad
v0.5.6, the template can reference [Node attributes and metadata][nodevars]. For
a full list of the API template functions, please refer to the [Consul Template
README][ct].
## `template` Parameters
@ -137,7 +138,24 @@ template {
}
```
### Client Configuration
### Node Variables
As of Nomad v0.5.6 it is possible to access the Node's attributes and metadata.
```hcl
template {
data = <<EOH
---
node_dc: {{ env "node.datacenter" }}
node_cores: {{ env "attr.cpu.numcores" }}
meta_key: {{ env "meta.node_meta_key" }}
EOH
destination = "local/file.yml"
}
```
## Client Configuration
The `template` block has the following [client configuration
options](/docs/agent/config.html#options):
@ -148,3 +166,4 @@ options](/docs/agent/config.html#options):
[ct]: https://github.com/hashicorp/consul-template "Consul Template by HashiCorp"
[artifact]: /docs/job-specification/artifact.html "Nomad artifact Job Specification"
[env]: /docs/runtime/environment.html "Nomad Runtime Environment"
[nodevars]: /docs/runtime/interpolation.html#interpreted_node_vars "Nomad Node Variables"