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

Helm依赖模板函数certificate-enabled返回值异常排查

问题排查:Helm模板函数始终返回false导致Secret未渲染

问题背景

主Chart test-service 依赖辅助Chart helm-common-templates,辅助Chart中定义了helm-common-templates.certificate-enabled函数,用于判断global.pms.logstash.tls.enabled是否为true,返回字符串"true"或"false"。主Chart的certificate.yaml调用该函数,但通过--set global.pms.logstash.tls.enabled=true执行helm dry-run时,Secret资源未被渲染,函数始终返回false。

相关代码与环境

辅助Chart函数代码

{{- define "helm-common-templates.certificate-enabled" -}}
{{- $val := "false" }}
{{- if .Values.global -}}
{{- if .Values.global.pms -}}
{{- if .Values.global.pms.logstash -}}
{{- if .Values.global.pms.logstash.tls -}}
{{- if .Values.global.pms.logstash.tls.enabled -}}
{{- $val := "true" }}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{ $val }}
{{- end -}}

主Chart certificate.yaml内容

{{ if eq (include "helm-common-templates.certificate-enabled" .) "true" }}

apiVersion: v1
kind: Secret
type: Opaque
metadata:
  name: ls-secret
  annotations:
    "helm.sh/hook": "post-delete"
    "helm.sh/hook-delete-policy": "before-hook-creation, hook-succeeded"
data:

---
{{end}}

dry-run命令

helm upgrade --install --debug  test --namespace bcc --wait --timeout "10m0s"  --set global.pms.logstash.tls.enabled=true  . --dry-run

dry-run输出(关键部分)

USER-SUPPLIED VALUES:
global:
  pms:
    logstash:
      tls:
        enabled: true

COMPUTED VALUES:
global:
  pms:
    logstash:
      tls:
        enabled: true
...
MANIFEST:

原因分析

函数中存在变量作用域问题:在if .Values.global.pms.logstash.tls.enabled块内使用{{- $val := "true" }}时,:=是创建新的局部变量,而非修改外层已经声明的$val。因此外层的$val始终保持初始值"false",导致函数返回结果不符合预期。

解决方案

方案1:修正变量赋值方式

将函数内的局部变量声明改为赋值操作,使用=而非:=,直接修改外层变量:

{{- define "helm-common-templates.certificate-enabled" -}}
{{- $val := "false" }}
{{- if .Values.global -}}
{{- if .Values.global.pms -}}
{{- if .Values.global.pms.logstash -}}
{{- if .Values.global.pms.logstash.tls -}}
{{- if .Values.global.pms.logstash.tls.enabled -}}
{{- $val = "true" }}  # 替换:=为=,修改外层变量值
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{ $val }}
{{- end -}}

方案2:简化函数逻辑(推荐)

利用Go模板的索引链和默认值特性,简化函数写法,避免多层嵌套和变量作用域问题:

{{- define "helm-common-templates.certificate-enabled" -}}
{{- printf "%t" (default false .Values.global.pms.logstash.tls.enabled) -}}
{{- end -}}

说明:default false会在路径不存在时返回false,printf "%t"将布尔值转为字符串"true"/"false",和原函数逻辑一致但更简洁。

验证步骤

  1. 修改辅助Chart的_helpers.tpl中的函数代码
  2. 重新执行dry-run命令:
    helm upgrade --install --debug  test --namespace bcc --wait --timeout "10m0s"  --set global.pms.logstash.tls.enabled=true  . --dry-run
    
  3. 检查MANIFEST部分是否出现ls-secret的Secret资源定义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 06:55:22