List of nested Key-value pairs

Hey! I need some figuring out how process a nested list in Consul’s Key-value store with Consul Template.

My data is stored this way:
kv/service/data/config/process/servers/0/name → string_value
kv/service/data/config/process/servers/0/enabled → boolean_value

kv/service/data/config/process/servers/1/name → string_value
kv/service/data/config/process/servers/1/enabled → boolean_value

I’ve followed Consul-template documentation but for the life of me, I can’t seem to get my head around how to retrieve these nested values.

If possible, I’d like to generate an output like the following:

            name: <server_name>
            enabled: <boolean>
            name: <server_name>
            enabled: <boolean>

Is this possible to achieve with Consul-template?

Hey @jalexander, thanks for asking.

What you want should be possible but how requires a quick initial question… Those entries under servers:, are they fixed so there is always a 0 and 1 (with name/enabled) or is that a variable length list of servers (0…N) that should be generated when the template is run?

Thanks for your response. (0…N) as its possible it will be initialized with an empty list if there are no servers.

Managed to figure it out… Here’s the approach I took:

  {{ range $key, $pairs := tree "service/data/config/process/servers/owners" | byKey }}{{ $key }}:
    {{ range $pair := $pairs}}
  {{ end }}{{ end }}

:smile: Exactly the same code that I came up with but you beat me to it.
Glad you figured it out!

1 Like