Home > Software design >  Helm Convert chart labels multiline string to comma-separated string
Helm Convert chart labels multiline string to comma-separated string

Time:10-01

I have labels as multiline string in _helpers.tpl as below. How can i convert this into comma separated list.

_helpers.tpl:-

{{- define "mongo.selectorLabels" -}}
app: {{ include "mongo.name" . }}
release: {{ .Release.Name }}
{{- end }}

Expecting:

teplates/yaml:-

          env:
            - name: MONGO_SIDECAR_POD_LABELS
              value: "{{- include "mongo.sidecar.pod.labels" . }}"

value: "app=mongo,release=dev"

Pseudo code i am trying.

_helpers.tpl:-

{{- define "mongo.sidecar.pod.labels" -}}
{{- $list := list -}}
{{- range $k, $v := ( include "mongo.selectorLabels" ) -}}
{{- $list = append $list (printf "%s=\"%s\"" $k $v) -}}
{{- end -}}
{{ join ", " $list }}
{{- end -}}

CodePudding user response:

The Helm include extension function always returns a string; so you can't use range to iterate over it as you've shown. However, Helm also includes an undocumented fromYaml extension function that can convert a YAML-format string back to object form. So if you include the helper template, then invoke fromYaml to parse the string result, you can range over the result:

{{- range $k, $v := include "mongo.selectorLabels" | fromYaml -}}

CodePudding user response:

I am able convert the values into = separated key-value pairs. How can we join these with , and merge as single line.

{{- define "mongo.sidecar.pod.labels" -}}
{{ $lines := splitList "\n" ( include "mongo.selectorLabels" .| nindent 1) -}}
{{- range $lines }}
{{- if not (. | trim | empty) -}}
{{- $kv := . | splitn ":" 2 -}}
{{ printf "%s=%s" $kv._0 ($kv._1 | trim) }}
{{ end -}}
{{- end -}}
{{- end -}}

Output with the above code:-

         env:
            - name: MONGO_SIDECAR_POD_LABELS
              value: " app=mongo
 release=v1
" 
  • Related