You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Helm循环内调用template函数报错,求正确上下文使用方案

解决Helm模板循环内调用template函数时的上下文问题

你遇到的问题核心是Helm模板的上下文作用域变化:当你在range .Values.allowedNamespaces循环内部时,.已经不再指向Chart的根上下文(包含.Values、.Release等顶层对象的那个上下文),而是变成了当前遍历到的单个命名空间字符串。这时候你把这个字符串传给traefik.deployNamespace模板,模板里尝试访问.Values.deployNamespace自然会报错——因为字符串类型里根本没有Values字段。

两种快速修复方案

方案1:提前保存根上下文到变量

在循环开始前,把根上下文赋值给一个变量(比如$root),然后在循环内调用模板时传入这个变量:

# 遍历允许的命名空间并创建角色
{{- if .Values.allowedNamespaces }}
{{- $root := . -}}  # 保存根上下文到$root变量
{{- range .Values.allowedNamespaces }}
# 命名空间规则: {{ . }}
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: {{ . }}-traefik-ingress-r
  namespace: {{ . }}
rules:
- apiGroups:
  - ""
  resources:
  - services
  - endpoints
  - secrets
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - extensions
  resources:
  - ingresses
  verbs:
  - get
  - list
  - watch
---
kind: RoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
  name: {{ . }}-traefik-ingress-rb
  namespace: {{ . }}
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: {{ . }}-traefik-ingress-r
subjects:
- kind: ServiceAccount
  name: traefik-ingress-sa
  namespace: {{ template "traefik.deployNamespace" $root }}  # 传入根上下文
{{- end }}
{{- end }}

方案2:直接使用$引用根上下文

Helm模板里的$符号始终指向根上下文,所以你可以跳过变量赋值,直接把$传给模板:

# ... 其他代码不变
subjects:
- kind: ServiceAccount
  name: traefik-ingress-sa
  namespace: {{ template "traefik.deployNamespace" $ }}  # 用$直接引用根上下文
{{- end }}

额外说明

你的traefik.deployNamespace模板定义本身是没问题的,它期望接收的是包含.Values的根上下文。只要确保调用模板时传入的是正确的上下文,就能正常解析.Values.deployNamespace了。

执行helm template .时,两种方案都能解决你遇到的can't evaluate field Values in type string错误。

内容的提问来源于stack exchange,提问作者Alfredo Palhares

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:02:53