Help with Consul template

Hi

I am trying to build a dynamic config for Caddyfile:

I would like to iterate over services and watch out for a tag caddy=<namespace>

As an example, having a service grafana having tags:

  • caddy=default

The result should look like:

# grafana in default -> grafana.example.com
grafana.example.com {
  import auth_snippet
  import revproxy_snippet grafana.service
}

In the caddy job definition, I use

variable "domain" {
  type = string
}

And pass the variable with -var-file, but I noticed, I can not access the NOMAD_VAR_domain with env like I do with NOMAD_NAMESPACE:

{{ $namesapce := env "NOMAD_NAMESPACE" -}}
{{ $domain := env "NOMAD_VAR_domain" -}}

{{ range $tag, $services := services | byTag -}}
{{ if eq $tag (print "caddy=" $namesapce) -}}{{ range $services -}}
# {{ .Name }} in {{ $namesapce }} -> {{.Name }}.{{ $domain }}
{{ .Name }}.{{ $domain }} {
  import auth_snippet
  import revproxy_snippet {{ .Name }}.service
}
{{ end }}{{ end }}{{ end }}

Is there another way to achive that?

Hey @resmo

Since HCL2 is rendered at submit time, you can access the HCL variable values using the standard interpolation syntax—${var.domain} based on your example. This value will be materialized as a constant once you submit the job.

To put this into your context:

{{ $namesapce := env "NOMAD_NAMESPACE" -}}
{{ $domain := ${var.domain} -}}

{{ range $tag, $services := services | byTag -}}
{{ if eq $tag (print "caddy=" $namesapce) -}}{{ range $services -}}
# {{ .Name }} in {{ $namesapce }} -> {{.Name }}.{{ $domain }}
{{ .Name }}.{{ $domain }} {
  import auth_snippet
  import revproxy_snippet {{ .Name }}.service
}
{{ end }}{{ end }}{{ end }}

One note about this behavior. If your templates need to output ${...} tokens, you have to escape the $ by converting it to $$ or you will receive errors.

Hope this helps,
Charlie

1 Like

Thanks for the help, just for the record, I had to quote it:

{{ $domain := "${var.domain}" -}}

Good catch, thanks for posting that. :man_facepalming: I should have run the job locally. I’m glad it got you sorted.

1 Like