Read key with prefix

Hello, I currently have informations saved under this form in consul:

env1
  domain=env1.test.com
env2
  domain=env2.test.com

I hoped I could have a template to render my config and set a prefix at execution when running consul-template with the prefix set in that case to env1 or env2.
I could not find any way to do that so here I am.

Here is an exemple of what the template could be:

{{ key "domain" }}

Is there any ?

Hi @schmurfy,

You can achieve this using the following template.

{{- $env := (env "ENVIRONMENT") -}}
{{ key (print $env "/domain") }}

The target environment / prefix is provided as an environment variable when executing consul-template. The variable is read using the env function, and stored in the internal template variable called $env. Finally, $env and the desired key name are concatenated using print before passing the resultant string (i.e., “env1/domain”) is passed to key for the lookup.

$ ENVIRONMENT=env1 consul-template -once -template "prefix.ctmpl:domain.txt" -dry
> domain.txt
env1.test.com

$ ENVIRONMENT=env2 consul-template -once -template "prefix.ctmpl:domain.txt" -dry
> domain.txt
env2.test.com
1 Like