使用 Helm 模板时无法评估字符串类型中的字段值

Pil*_*hae 5 kubernetes-helm helm3

我有如下的 k8s 清单,用 Helm 打包。

apiVersion: v1
kind: ServiceAccount
metadata:
  {{- template "myFunction" "blah" -}}
Run Code Online (Sandbox Code Playgroud)

我将_helper.tplmyFunction 定义如下。

{{- define "myFunction" }}
  {{- if .Values.nameOverride }}
  name: {{ . }}
  {{- else }}
  name: "test"
  {{- end }}
{{- end }}
Run Code Online (Sandbox Code Playgroud)

最后,我values.yaml定义了nameOverride: "". 根据我的理解,由于我没有为 nameOverride 定义任何内容,因此myFunction应该输出name: "test",当我为 nameOverride 定义某些内容时,输出应该为name: "blah"。但是,我收到以下错误。

Error: template: product-search/templates/_helpers.tpl:2:16: executing "myFunction" at <.Values.nameOverride>: can't evaluate field Values in type string
helm.go:88: [debug] template: product-search/templates/_helpers.tpl:2:16: executing 
"myFunction" at <.Values.nameOverride>: can't evaluate field Values in type string
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?谢谢!

Dav*_*aze 6

在 Gotext/template语言中,是对特殊变量 中.Values命名的字段的查找。该变量在不同的上下文中会改变含义。在模板内部,从模板的参数值开始,该值不一定是顶级 Helm 对​​象。Values.define.

{{ template "myFunction" "blah" }}

{{ define "myFunction" }}
{{/* with the call above, . is the string "blah" */}}
{{ end }}
Run Code Online (Sandbox Code Playgroud)

一个模板只需要一个参数。您可以在这里做几件事。一种方法是找出调用者中的字段值,并将其作为模板参数传递:

{{-/* Emit a name: label.  The parameter is a string. */-}}
{{- define "myFunction" -}}
name: {{ . }}
{{ end -}}

{{-/* if .Values.nameOverride then "blah" else "test" */-}}
{{- $label := ternary "blah" "test" .Values.nameOverride -}}
{{ include "myFunction" $label | indent 4 }}
Run Code Online (Sandbox Code Playgroud)

另一种方法是将这两个值打包到一个参数中。我倾向于使用 Helmlist函数来实现此目的。然而,这使得模板逻辑变得更加复杂。

{{/* Emit a name: label.  The parameter is a list of two values,
     the top-level Helm object and the alternate label name to use
     if .Values.nameOverride is defined. */}}
{{- define "myFunction" -}}
{{/* . is a list of two values; unpack them */}}
{{- $top := index . 0 -}}
{{- $label := index . 1 -}}
{{/* Now we can look up .Values within the passed top-level object */}}
{{- if $top.Values.nameOverride -}}
name: {{ $label }}
{{ else -}}
name: "test"
{{ end -}}
{{- end -}}

{{/* When calling the function manually construct the parameter list */}}
{{ include "myFunction" (list . "blah") | indent 4 }}
Run Code Online (Sandbox Code Playgroud)