Template environment variables are not referenced in further template files

I discovered a strange behavior after migration from static environment variables in a job task definition to dynamic environment variables via template as described here:

It seems the variables that are created within the template are not parsed in further templated configuration files within the tasks.

The nomad client is a windows node and the task driver is java.

The template stanza that contains the environment:

      template {
        data = <<EOH
DB_HOST="{{ with service "mssql" }}{{ with index . 0 }}{{.Address}}{{ end }}{{ end }}"
DB_PORT="{{ with service "mssql" }}{{ with index . 0 }}{{ .Port }}{{ end }}{{ end }}"
DB_USER="foo"
DB_PASSWORD="bar"
EOH
        env = true
        destination = "local/env"
      }

The template that is using the variables:

                <mandatoryFields>
                        <database host="{{ env "DB_HOST" }}" port="{{ env "DB_PORT" }}" dbName="{{ env "DB_NAME" }}" user="{{ env "DB_USER" }}" password="{{ env "DB_PASSWORD" }}" />
                        <logging logDir="./local/logs" maxArchiveAge="1" asynchronous="true" maxSize="1" maxFileCount="10" >
                        </logging>
                        <portShared>{{ env "NOMAD_PORT_server" }}</portShared>
                </mandatoryFields>

The template stanza for this config is below the environment template. The data part is created within terraform and terraform nomad provider.

      template {
        data = <<EOF
${serverconf_override_xml}
EOF
        destination = "local/conf/serverconf.override.xml"
      }

afaik, template blocks are not chained; they are separate, individual fetches from Consul (or Vault).

I think you may need to put the entire {{ ... }} code blocks wherever you require it.

If the above does solve your problem, you might also be interested in the file function, which lets you store the template data outside of the .nomad job file (in case you want less clutter in the job file itself).

HTH,
Shantanu Gadgil

1 Like

Hi @gthieleb :wave:

@shantanugadgil is absolutely right, there is no inherit dependency between template blocks, and they are actually handled in parallel :slightly_smiling_face:

You would need to redefine these variables in the template that uses them.

1 Like

Thanks to both of you for your answer. I was under the assumption that templates that creates the env variables (indicated by the keyword env = true) are prioritized on task initialising before loading other (non env) templates.

That sounds like a reasonable request :thinking:

Would mind filing a feature request so we can keep track of it?

Thanks!