简体   繁体   中英

Helm Convert chart labels multiline string to comma-separated string

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 -}}

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 -}}

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
" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM