Helm升级时如何仅创建不存在的Secret,复用已有Secret?
问题原因与解决方案
你的核心问题是lookup函数的Secret名称参数写法错误,导致查询不到已存在的Secret,每次upgrade都会触发新密码生成。
在原代码中,lookup的第三个参数写为"{{.Release.Namespace}}-mongodb-secret",这是将模板语法作为字符串字面量传入,而非解析后的实际Secret名称(比如命名空间为default时,实际要查的是default-mongodb-secret,但代码里查的是字面量{{.Release.Namespace}}-mongodb-secret),自然找不到已存在的Secret,只能走默认的随机密码生成逻辑。
修正后的代码
apiVersion: v1 kind: Secret metadata: name: "{{.Release.Namespace}}-mongodb-secret" type: Opaque data: {{- /* 先生成正确的Secret名称,避免嵌套模板语法解析错误 */}} {{- $secretName := printf "%s-mongodb-secret" .Release.Namespace }} {{- $secretObj := (lookup "v1" "Secret" .Release.Namespace $secretName) | default dict }} {{- $secretData := (get $secretObj "data") | default dict }} {{- $mongodbpasswords := (get $secretData "mongodb-passwords") | default (randAlphaNum 8 | b64enc) }} mongodb-passwords: {{ $mongodbpasswords | quote }} {{- $mongodbrootpassword := (get $secretData "mongodb-root-password") | default (randAlphaNum 8 | b64enc) }} mongodb-root-password: {{ $mongodbrootpassword | quote }}
关键说明
- 正确生成Secret名称:用
printf拼接命名空间和固定后缀,生成实际要查询的Secret名称,确保lookup能找到已存在的资源。 - 权限检查:确保执行helm upgrade的账号拥有对应命名空间下Secret的
get权限,否则lookup会失败,依然会生成新密码。 - Helm版本要求:lookup函数仅在Helm 3及以上版本支持,若使用旧版本需升级。
内容的提问来源于stack exchange,提问作者windowws
相关产品推荐
相关产品推荐

