Helm 将图表标签多行字符串转换为逗号分隔的字符串

Helm Convert chart labels multiline string to comma-separated string

我在 _helpers.tpl 中将标签作为多行字符串,如下所示。我如何将其转换为逗号分隔列表。

_helpers.tpl:-

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

期待:

teplates/yaml:-

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

value: "app=mongo,release=dev"

我正在尝试的伪代码。

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

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 扩展函数,可以将 YAML 格式的字符串转换回对象形式。因此,如果您 include 辅助模板,然后调用 fromYaml 来解析字符串结果,您可以 range 覆盖结果:

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

我可以将值转换为 = 分隔的键值对。我们如何将它们与 , 连接起来并合并为单行。

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

以上代码输出:-

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