Helm3模板嵌套调用问题:引用内部模板时出现报错
Helm v3.9.2模板嵌套调用报错:invalid value; expected string
问题背景
使用Helm自动生成的标准app.fullname模板,在自定义模板app.userSessionSelector中嵌套调用时触发错误,但该模板在项目其他场景下可正常解析。
标准app.fullname模板
{{/* Create a default fully qualified app name. We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). If release name contains chart name it will be used as a full name. */}} {{- define "app.fullname" -}} {{- if .Values.fullnameOverride }} {{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} {{- else }} {{- $name := default .Chart.Name .Values.nameOverride }} {{- if contains $name .Release.Name }} {{- .Release.Name | trunc 63 | trimSuffix "-" }} {{- else }} {{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} {{- end }} {{- end }} {{- end }}
自定义app.userSessionSelector模板
{{- define "app.userSessionSelector" -}} workload.user.cattle.io/workloadselector: deployment-{{ .Release.Namespace }}-{{ include "app.fullname" . }}-usersession {{- end }}
报错信息
Error: Failed to render chart: exit status 1: install.go:178: [debug] Original chart version: "" install.go:195: [debug] CHART PATH: /home/user/helm/app Error: template: app/templates/_helpers.tpl:70:81: executing "app.userSessionSelector" at <include "app.fullname" .>: error calling include: template: app/templates/_helpers.tpl:18:16: executing "app.fullname" at <$name>: invalid value; expected string helm.go:84: [debug] template: app/templates/_helpers.tpl:70:81: executing "app.userSessionSelector" at <include "app.fullname" .>: error calling include: template: app/templates/_helpers.tpl:18:16: executing "app.fullname" at <$name>: invalid value; expected string
问题原因
报错核心是调用app.userSessionSelector时传递的上下文(.)并非完整的Helm根上下文。app.fullname依赖.Chart.Name、.Values.nameOverride等根上下文字段,若传递的是子上下文(比如range循环中的单个元素、资源的子字段),会导致$name := default .Chart.Name .Values.nameOverride无法获取有效字符串,触发类型错误。
其他场景调用app.fullname正常,是因为那些场景传递的都是完整的根上下文。
解决方案
方案1:确保调用时传递根上下文
检查调用app.userSessionSelector的代码,根据当前上下文传递正确的根引用:
- 根级别调用时直接传递
.:{{ include "app.userSessionSelector" . }} range循环等子上下文场景,用$指代根上下文:{{ range .Values.someResources }} metadata: annotations: {{ include "app.userSessionSelector" $ }} {{ end }}
方案2:修改模板强制绑定根上下文
在app.userSessionSelector内部先捕获根上下文,避免依赖调用时的传递内容:
{{- define "app.userSessionSelector" -}} {{- $root := . -}} workload.user.cattle.io/workloadselector: deployment-{{ $root.Release.Namespace }}-{{ include "app.fullname" $root }}-usersession {{- end }}
修改后执行helm template或helm install --dry-run验证,确认报错消失。
内容的提问来源于stack exchange,提问作者Rafał W.
相关产品推荐
相关产品推荐

