Tag: helm

helm charts identify last element of list in range

helm charts identify last element of list in range

If you are reading this then most likely you are struggling to identify last element of the list in helm templates. go on read on for answer:

Helm template:


---
[{{- $root := . -}}
{{- $lastIndex := sub (len $root.Values.config.hosts) 1}}
{{- range $i, $host := $root.Values.config.hosts }}
  {
    "host" : {{ $host }},
    "index" : {{ $i }}
  }{{- if ne $i $lastIndex -}}, {{ end }}
{{- end }}
]

when provided following values:


---
config:
  hosts: ["host1", "host2"]

results in:


[
  {
    "host" : "host1",
    "index" : "0"
  },
  {
    "host" : "host2",
    "index" : "1"
  }
]

Observe there is no comma after 2nd hash object.