首页 > 解决方案 > 如何定义模板函数以在 Helm 中设置全局或局部容差?

问题描述

我想检查是否tolerations可用,global然后将其用于所有 pod(带有子图表的父图表),如果每个子模块/子图表都有自己的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 部署堆栈时,我将 a 传递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"

标签: kubernetes-helm

解决方案


我在编写的代码中看到了两个问题。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 */}}

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

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

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


推荐阅读