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

2023-12-31

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

apiVersion: v1
kind: ServiceAccount
metadata:
  {{- template "myFunction" "blah" -}}

I have _helper.tpl定义 myFunction 如下。

{{- define "myFunction" }}
  {{- if .Values.nameOverride }}
  name: {{ . }}
  {{- else }}
  name: "test"
  {{- end }}
{{- end }}

最后,我有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

有什么想法吗?谢谢!


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

{{ template "myFunction" "blah" }}

{{ define "myFunction" }}
{{/* with the call above, . is the string "blah" */}}
{{ end }}

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

{{-/* 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 }}

另一种方法是将这两个值打包到一个参数中。我倾向于使用头盔list为此功能。然而,这使得模板逻辑变得更加复杂。

{{/* 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 }}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐