Helm: generate comma separated list

alfred picture alfred · Dec 6, 2017 · Viewed 16.8k times · Source

Using Helm templates, I'm trying to generate a list of server names based on a number in values.yaml. The dot for this template is set to the number (its a float64).

{{- define "zkservers" -}}
{{- $zkservers := list -}}
{{- range int . | until -}}
{{- $zkservers := print "zk-" . ".zookeeper" | append $zkservers -}}
{{- end -}}
{{- join "," $zkservers -}}
{{- end -}}

For an input of, say, 3 I'm expecting this to produce:

zk-0.zookeeper,zk-1.zookeeper,zk-2.zookeeper

It produces nothing.

I understand that the line within the range block is a no-op since the variable $zkservers is a new variable each time the loop iterates. It is not the same variable as the $zkservers in the outer scope.

I hope the intention is clear of what I want to do. I am at a loss how to do it.

Anyone know how to do this with Helm templates?

Answer

Pete Birley picture Pete Birley · Sep 23, 2018

Another quick way of doing it:

{{- define "helm-toolkit.utils.joinListWithComma" -}}
{{- $local := dict "first" true -}}
{{- range $k, $v := . -}}{{- if not $local.first -}},{{- end -}}{{- $v -}}{{- $_ := set $local "first" false -}}{{- end -}}
{{- end -}}

If you give this input like:

test:
- foo
- bar

And call with:

{{ include "helm-toolkit.utils.joinListWithComma" .Values.test }}

You'll get the following rendered:

foo,bar

This is from OpenStack-Helm's Helm-toolkit chart, which is a collection of utilities for similar purposes.