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

Helm遍历复杂values.yaml数据报错,求正确模板写法

Helm模板遍历pubSub生成环境变量报错修复

问题背景

需要通过Helm的.tpl模板遍历values.yaml中的pubSub结构,生成指定格式的Topic和Subscription环境变量列表,但执行helm template . --debug时出现错误:can't evaluate field topicName in type int。

相关配置

values.yaml

pubSub:
  - topicName: topic-1
    topicEnvVar: TOPIC_1
    subscriptions:
      - subscriptionName: subscription-1
        subscriptionEnvVar: SUBSCRIPTION_1
      - subscriptionName: subscription-2
        subscriptionEnvVar: SUBSCRIPTION_2
  - topicName: topic-2
    topicEnvVar: TOPIC_2
    subscriptions: {}
  - topicName: topic-3
    topicEnvVar: TOPIC_3
    subscriptions: {}

当前错误模板

{{- range $topic, $envVar := .Values.pubSub }}
- name: {{ $envVar }}
  value: {{ $topic.topicName }}
{{- range $subName, $subEnvVar := $topic.subscriptions }}
- name: {{ $subEnvVar }}
  value: {{ $subName }}
{{- end }}
{{- end }}

期望输出
Topic环境变量:

- name: TOPIC_1
  value: topic-1
- name: TOPIC_2
  value: topic-2
- name: TOPIC_3
  value: topic-3

Subscription环境变量:

- name: SUBSCRIPTION_1
  value: subscription-1
- name: SUBSCRIPTION_2
  value: subscription-2

错误信息

Error: template: chart/templates/deployment.yaml:38:16: executing "chart/templates/deployment.yaml" at <include "chart.envVarsFull" .>: error calling include: template: chart/templates/_envVarsHelper.tpl:77:18: executing "chart.envVarsFull" at <$topic.topicName>: can't evaluate field topicName in type int

helm.go:84: [debug] template: chart/templates/deployment.yaml:38:16: executing "chart/templates/deployment.yaml" at <include "chart.envVarsFull" .>: error calling include: template: chart/templates/_envVarsHelper.tpl:77:18: executing "chart.envVarsFull" at <$topic.topicName>: can't evaluate field topicName in type int

错误原因

Helm模板中range遍历列表时,若使用$key, $value的形式,第一个变量是列表的索引(整数类型),第二个变量才是列表中的元素对象。原模板中把$topic设为索引(int),$envVar设为元素,导致访问$topic.topicName时,试图在整数类型上访问字段,触发报错。

修正后的模板

将遍历变量的顺序调整正确,或者直接使用单变量遍历元素:

{{- range $topicItem := .Values.pubSub }}
# 生成Topic环境变量
- name: {{ $topicItem.topicEnvVar }}
  value: {{ $topicItem.topicName }}
# 生成Subscription环境变量(仅当subscriptions非空时)
{{- if $topicItem.subscriptions }}
{{- range $subItem := $topicItem.subscriptions }}
- name: {{ $subItem.subscriptionEnvVar }}
  value: {{ $subItem.subscriptionName }}
{{- end }}
{{- end }}
{{- end }}

模板说明

  1. 外层range直接遍历.Values.pubSub的每个元素,赋值给$topicItem,避免索引混淆。
  2. 直接访问$topicItem的topicEnvVar和topicName生成Topic环境变量。
  3. 内层遍历$topicItem.subscriptions的每个元素,赋值给$subItem,访问其subscriptionEnvVar和subscriptionName生成Subscription环境变量。
  4. 添加{{- if $topicItem.subscriptions }}判断,避免遍历空的subscriptions(原values中存在subscriptions: {}的情况)。

验证结果

执行helm template . --debug后,将生成符合期望的环境变量列表,包含所有Topic和Subscription的配置,且无报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:25:31