Use hostname in template?

This cannot possibly be that difficult, but I cannot figure out how to get the hostname value in a consul (really, vault) template.

The basic problem is that I’m trying to use pkiCert to get a certificate for consul from vault. Since consul needs the certificate before it can talk to the consul server, I can’t use .Node.name - afaik because consul isn’t up yet. I have to use the hostname if that’s what I want for the cert’s CN when I call vault’s .../issue

Some examples have shown using {{ with $host := env "HOSTNAME" }} - which seems to just give me an empty value and others have gone to creating custom go functions within the template itself(?), which I’m struggling to comprehend.

{{ with pkiCert "/pki/issue/node-dot-consul" "common_name=1-2-3-4.node.consul" }}
{{ .Data.Cert }}
{{ end }}

Is it possible to replace 1-2-3-4 with a variable of the hostname in that template code?

oi. $host wasn’t working because %q is the wrong placeholder I guess. Switching to %s was the trick.

This does in fact work:

{{ $cn_arg := printf "common_name=%s.node.consul" (env "HOSTNAME") }}
{{ with pkiCert "/pki/issue/node-dot-consul" $cn_arg }}
{{ .Data.Cert }}
{{ end }}
2 Likes

I’m a real noob at go templates. where is the documentation for the ‘env’ function you are calling? The only thing I can really find is this https://docs.gomplate.ca/functions/env/ but it doesn’t explain how you are just calling ‘env’ and passing it a value. I know this is probably super simple. Even referencing this template into something like https://gotemplate.io/ is just giving me errors.

Your answer has helped me and I appreciate you taking the tome to post about it!

Go’s text/template package defines the base template language, but each application that integrates it is able to add more functions.

The additional functions that consul-template adds to the language, including env, are described at consul-template/templating-language.md at main · hashicorp/consul-template · GitHub

1 Like

Thank you! I will check this out. Much appreciated