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

**URL:** <https://discuss.hashicorp.com/t/parsing-paths-to-a-key-value-tree-with-consul-template/26425>\
**Category:** Consul\
**Tags:** consul-template\
**Created:** [July 6, 2021, 5:26pm UTC](https://discuss.hashicorp.com/t/parsing-paths-to-a-key-value-tree-with-consul-template/26425 "2021-07-06T17:26:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bsg-sfrazer](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/bsg-sfrazer/32/20569_2.png) [@bsg-sfrazer](https://discuss.hashicorp.com/u/bsg-sfrazer)\
**Post date:** [July 6, 2021, 5:26pm UTC](https://discuss.hashicorp.com/t/parsing-paths-to-a-key-value-tree-with-consul-template/26425/1 "2021-07-06T17:26:12Z")

</div>

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

```auto
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:

```auto
{{ 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:

```auto
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!

---

<div class="post-metadata">

**Author:** ![blake](https://sea2.discourse-cdn.com/hashicorp/user_avatar/discuss.hashicorp.com/blake/32/27620_2.png) [@blake](https://discuss.hashicorp.com/u/blake)\
**Post date:** [July 6, 2021, 7:58pm UTC](https://discuss.hashicorp.com/t/parsing-paths-to-a-key-value-tree-with-consul-template/26425/2 "2021-07-06T19:58:50Z")

</div>

Hi @bsg-sfrazer,

The [`byKey`](https://github.com/hashicorp/consul-template/blob/master/docs/templating-language.md#bykey) function available in Consul template should help give you the output you’re looking for.

```go
# customer-template.ctmpl
{{- range $key, $pairs := tree "/portal/sites/" | byKey -}}
{{ $key }}:
  {{- range $pair := $pairs }}
    {{ .Key }}: {{ .Value }}
  {{- end }}
{{ end }}

```

```auto
$ 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

```
