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 }}
模板说明
- 外层
range直接遍历.Values.pubSub的每个元素,赋值给$topicItem,避免索引混淆。 - 直接访问
$topicItem的topicEnvVar和topicName生成Topic环境变量。 - 内层遍历
$topicItem.subscriptions的每个元素,赋值给$subItem,访问其subscriptionEnvVar和subscriptionName生成Subscription环境变量。 - 添加
{{- if $topicItem.subscriptions }}判断,避免遍历空的subscriptions(原values中存在subscriptions: {}的情况)。
验证结果
执行helm template . --debug后,将生成符合期望的环境变量列表,包含所有Topic和Subscription的配置,且无报错。
内容的提问来源于stack exchange,提问作者KrisM4c
相关产品推荐
相关产品推荐

