Helm 3,将 values.yaml 中的对象数组转换为逗号分隔的字符串

Helm 3, convert array of objects in values.yaml into comma separated string

我在 values.yaml 文件中有以下结构:

upstreams:
- service_name: service_a
  mapped_port: 1000
- service_name: service_b
  mapped_port: 1001

我希望在我的 deployment.yaml 模板中像这样呈现:

"service-upstreams": "service_a:1000, service_b:1001"

知道怎么做吗?

您需要遍历 upstreams 值中的对象并连接这些值。

上游助手模板的定义

templates/_helpers.tpl

{{- define "sample.upstreams" -}}
{{- if .Values.upstreams }}
{{- range .Values.upstreams }}{{(print .service_name ":" .mapped_port ) }},{{- end }}
{{- end }}
{{- end }}

使用模板(在本例中作为标签)

templates/deployment.yaml

metadata:
  labels:
    {{- if .Values.upstreams }} 
    service-upstreams: {{- include "sample.upstreams" . | trimSuffix "," | quote }} 
    {{- end }}

我没有删除模板中的逗号,因为 trimSuffix 不接受大括号作为参数的一部分

我会参考 David Maze 链接的答案和 range 文档