Parsing paths to a key/value tree with consul-template

Assuming I have a consul key/value path that looks like this:

portal/sites/customer_a/owner_id = 1
portal/sites/customer_a/slug = alpha
portal/sites/customer_b/owner_id = 2
portal/sites/customer_b/slug = beta

How could I iterate through the “customer_a”/“customer_b” portion of this path?

I managed to get just that portion using regex like so:

{{ range tree "/portal/sites/" }}
{{ $shortname := .Key |	regexReplaceAll	"/.+" "" }}
{{ $fullpath :=	( $shortname | printf "/portal/sites/%s/") }}
{{ $shortname }}:{{ range $key, $pairs := tree $fullpath | explode }}
  {{ $key }}: {{ $pairs }}
{{- end }}{{ end }}

This is giving the output I expect, but it’s duplicating the results:

customer_a:
  friendly_name: alpha
  owner_id: 1

customer_a:
  friendly_name: alpha
  owner_id: 1

customer_b:
  friendly_name: beta
  owner_id: 2

customer_b:
  friendly_name: beta
  owner_id: 2
  • I only want one of them, not 2

Thanks!

Hi @bsg-sfrazer,

The byKey function available in Consul template should help give you the output you’re looking for.

# customer-template.ctmpl
{{- range $key, $pairs := tree "/portal/sites/" | byKey -}}
{{ $key }}:
  {{- range $pair := $pairs }}
    {{ .Key }}: {{ .Value }}
  {{- end }}
{{ end }}
$ consul-template -template customer-template.ctmpl:out.txt -dry -once
> out.txt
customer_a:
    owner_id: 1
    slug: alpha
customer_b:
    owner_id: 2
    slug: beta