Read key with prefix

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


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

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