In helmcharts, how to combine a list with multiple fields per element into a string?

Viewed 27

I have a list that has multiple fields per element, and I would need to concatenate it into a comma separated string that has fields foo and bar separated with a semicolon.

myList:
  - foo: "asdf"
    bar: "hnng"
  - foo: "meh"
    bar: "dunno"

For example, the above would need to be concatenated into "asdf;hnng,meh;dunno".

You could iterate through the list with range, but how would you then pass on that list to join? For example, the following should produce a list of strings, but how would I then pass it into join function?

{{- range .Values.myList }}
  - {{.foo}};{{.bar}}
{{- end}

=>

- asdf;hnng
- meh;dunno
2 Answers

The Go text/template language doesn't have a generic map function or anything else that would make it possible to transform a list into another list. You need to rewrite this to emit the whole string in one block, it's probably not going to be possible to construct an input to join.

When you iterate through the outer list, you can get the current index and then use that to decide whether to set a separator:

{{- $index, $item := range .Values.myList -}}
{{- if ne $index 0 -}},{{- end -}}
{{- $item.foo -}};{{- $item.bar -}}
{{- end -}}

It's possible to make this a lot more complicated - split out the individual item into its own template, change the loop to a recursive template call - but fundamentally you need to emit the list-item separators yourself.

values.yaml

myList:
  - foo: "asdf"
    bar: "hnng"
  - foo: "meh"
    bar: "dunno"

template

apiVersion: v1
kind: ConfigMap
metadata:
  name: test
data: 
  data: |-
    {{- $str := "" }}
    {{- range $i, $e := .Values.myList }}
    {{- if $i }}
    {{- $str = print $str "," }}
    {{- end }}
    {{- $str = print $str $e.foo ";" $e.bar }}
    {{- end }}
    {{- $str | nindent 4 }}

output

apiVersion: v1
kind: ConfigMap
metadata:
  name: test
data: 
  data: |-
    asdf;hnng,meh;dunno
Related