Consul-Template: Looping over a k/v pair and using the result in another key

Viewed 4540

Given the Consul keys:

flyway/tweedle/server: postgres
flyway/beetle/server: postgres
flyway/battle/server: mysql

service/tweedle/repo: fox/tweedle.git
service/beetle/repo: fox/beetle.git
service/battle/repo: fox/battle.git

I'm trying to loop through the top set, using the key to lookup values in the bottom set, using this code (that doesn't work):

{

  {{ range $key, $pairs :=tree "flyway/" | explode }}
        $key: {{ key "service/{{$key}}/repo" }}
  {{ end }}

}

to get:

tweedle: fox/tweedle.git
beetle: fox/beetle.git
battle: fox/battle.git
1 Answers

My colleague, Brian answered this in the support ticket with HashiCorp.

Just wanted to share the answer here, so that it would benefit others as well. This is how it can be done:

{
{{ range $key, $pairs := tree "flyway/" | explode }}
    {{ $name := $key }}
    {{ range $key, $pairs := tree ($name | printf "service/%s/") | explode }}
        {{ $name}}: {{ $pairs }}
    {{ end }}
{{ end }}
}
Related