【问题标题】:How to use template-ized value in the range function in Helm如何在 Helm 的范围函数中使用模板化值
【发布时间】:2020-02-15 10:32:20
【问题描述】:

我正在为 Prometheus 使用 helm chart,并计划为不同的环境提供一组不同的警报管理器文件。 现有图表的提取部分:

{{- $root := . -}}
{{- range $key, $value := .Values.alertmanagerFiles }}
  {{ $key }}: |
{{ toYaml $value | default "{}" | indent 4 }}
{{- end -}}

为了覆盖这部分,我定义了一个模板变量

{{- define "prometheus.alertmanagerFiles" -}}
{{- if .Values.alertmanagerFiles.custom -}}
    {{- printf "alertmanagerFiles_%s" .Values.cluster.env }}
{{- else -}}
    {{- default "default" .Values.alertmanagerFiles -}}
{{- end -}}
{{- end -}}

有了这个,我每个环境都有一个新变量 - 例如:alertmanagerFiles_dev 用于开发,但由于我缺乏知识而一无所知,我不知道如何在范围函数中使用模板化变量。

试过了,还是不行:

{{- $root := . -}}
{{- range $key, $value := template "prometheus.alertmanagerFiles" . }}
  {{ $key }}: |
{{ toYaml $value | default "{}" | indent 4 }}
{{- end -}}

任何帮助、线索或方向都会在这里帮助我。

【问题讨论】:

    标签: prometheus kubernetes-helm


    【解决方案1】:

    您无需为此自定义图表。相反,您可以在 helm installhelm upgrade 图表时为每个环境提供一组不同的值

    helm upgrade prometheus stable/prometheus --install -f values.dev.yaml
    

    这通常比在模板代码中放置一层间接层更容易和更可取。

    如果您确实想使用所示的间接层,您会受到 Go 模板的可能返回类型的限制。标准的 Go template 指令只写入输出,从不返回任何内容。 Helm has an include function 而是将渲染模板的内容作为字符串返回。不过,这是唯一可以从模板返回的东西。

    在您的情况下,prometheus.alertmanagerFiles 模板会生成一个字符串,因此您可以通过include 它来获取您想要包含的顶级值的名称。然后,您可以使用标准 Go 模板 index 函数从 .Values 中提取该项目。这大致看起来像:

    {{- $fileKey := include "prometheus.alertmanagerFiles" . }}
    {{- range $key, $value := index .Values $fileKey }}
    ...
    {{- end -}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 2017-09-27
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多