如何定义模板函数以设置 Helm 中全局或局部容差的容差?

How to define a template function to set tolerations either from global or from local tolerations in Helm?

我想检查 tolerations 是否在 global 中可用,然后将其用于所有 pods(带有子图表的父图表),如果每个 submodule/subchart 都有它自己的 tolerations 然后使用它而不是全局的。所以我是这样定义它的:

{{/* Set tolerations from global if available and if not set it from each module */}}
{{- define "helper.tolerations" }}
{{- if .globalTolerations.tolerations }}
tolerations:
  {{toYaml .globalTolerations.tolerations | indent 2}}
{{- else if (.localTolerations.tolerations) }}
tolerations:
  {{toYaml .localTolerations.tolerations | indent 2}}
{{- end }}
{{- end }}

在每个子图表中,我有这个:

spec:
  template:
    spec:
      containers:
        - name:  my-container-name
      {{toYaml (include "helper.tolerations" (dict "globalTolerations" .Values.global "localTolerations" (index .Values "ui-log-collector"))) | indent 6}}

values.yaml中的默认值定义如下:

global:
  tolerations: []
ui-log-collector:
  image: a.b.c
  tolerations: []
some-other-sub-charts:
  image: x.y.z
  tolerations: []

现在,当我想使用 helm 部署堆栈时,我传递一个 values.yaml 来覆盖 tolerations,如下所示:

global:
  tolerations:
    - key: "key1"
      operator: "Equal"
      value: "value1"
      effect: "NoSchedule"
    - key: "key1"
      operator: "Equal"
      value: "value1"
      effect: "NoExecute"
ui-log-collector:
  tolerations:
    - key: "key2"
      operator: "Equal"
      value: "value2"
      effect: "NoSchedule"
    - key: "key2"
      operator: "Equal"
      value: "value2"
      effect: "NoExecute"

通过此设置,我目前收到此错误:

 error converting YAML to JSON: yaml: line 34: could not find expected ':'

我尝试了不同的方法,但没有 toYaml 我得到:

Error: UPGRADE FAILED: error validating "": error validating data: ValidationError(Deployment.spec.template.spec.tolerations): invalid type for io.k8s.api.core.v1.PodSpec.tolerations: got "string", expected "array"

我在编写的代码中看到两个问题。 Go 模板生成文本输出,因此您无需对它们调用 toYaml。另外,当你调用 indent 时,它不知道当前行的缩进,所以如果你要 indent 一些东西,通常需要打开 {{ ... }} 模板表达式未缩进的行。

例如,调用本身应该如下所示:

spec:
  template:
    spec:
      containers:
        - name:  my-container-name
{{ include "helper.tolerations" (dict "globalTolerations" .Values.global "localTolerations" .Values.ui-log-collector) | indent 6}}
{{-/* at the first column; without toYaml */}}

在辅助函数中,使用 toYaml 是合适的(.Values 是复合对象而不是字符串)但是 indent 行再次需要从第一列开始。

tolerations:
{{toYaml .globalTolerations.tolerations | indent 2}}

您可能会发现使用 helm template 调试此类问题很有用;它会写出生成的 YAML 文件,而不是将其发送到集群。问题中的 toYaml 形式可能会将 tolerations: 块转换为 YAML 字符串,这在输出中非常明显。