如何使用kustomize configMapGenerator生成的带哈希名称替换Helm values.yaml配置
问题:如何自动将Kustomize生成的带哈希后缀ConfigMap名称同步到Helm Values配置
我使用kustomize生成各类configMap,示例配置如下:
# kustomization.yaml configMapGenerator: - name: my-config-path # <-- 原始配置名称 files: - file1.txt - file2.txt - ... - fileN.txt
生成的ConfigMap输出示例如下:
# my-configmap.yaml apiVersion: v1 data: file1.txt: | ... file2.txt: | ... fileN.txt | ... kind: ConfigMap metadata: name: my-config-path-mk89db6928 # <-- 名称末尾追加了哈希后缀
另一方面,我有一个第三方helm chart,需要按如下规则覆盖values.yaml配置:
# third-party-chart-values.yaml customArguments: - --config.dir=/config ... volumes: - mountPath: /config name: my-config-path # <--- 此处希望替换为实际生成的`my-config-path-mk89db6928` type: configMap
请问是否有方案可以将third-party-chart-values.yaml中的my-config-path,自动替换为my-configmap.yaml中生成的带哈希后缀的ConfigMap名称?注:ConfigMap内容变更时,对应的哈希值如mk89db6928也会同步变化。
回答
以下是两种生产环境常用的可行方案,可以根据你的部署流程选择:
方案1:使用Kustomize内置Helm渲染能力直接打通(推荐)
直接在Kustomize中声明要渲染的第三方Helm Chart,Kustomize会自动完成ConfigMap哈希后缀的替换,完全不用手动处理变量:
- 修改你的
kustomization.yaml,新增Helm Chart渲染配置:
# kustomization.yaml apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization # 保留你原有的configMapGenerator配置 configMapGenerator: - name: my-config-path files: - file1.txt - file2.txt - ... - fileN.txt # 新增helm chart渲染配置 helmCharts: - name: third-party-chart repo: 第三方Chart对应的Helm仓库地址 version: 你使用的Chart版本号 valuesInline: customArguments: - --config.dir=/config volumes: - mountPath: /config # 这里直接写ConfigMap原始名称即可,Kustomize会自动替换为带哈希后缀的最终名称 name: my-config-path type: configMap
- 执行构建命令即可一次性输出所有配置正确的资源:
kustomize build --enable-helm
后续ConfigMap内容变更导致哈希后缀更新时,Kustomize渲染Helm Chart时会自动同步修改挂载的ConfigMap名称,无需人工干预。
方案2:命令行提取名称后传入Helm(适合Kustomize、Helm分开部署的场景)
如果你的部署流程需要单独执行Kustomize构建和Helm渲染,可以通过命令行提取生成的ConfigMap名称,再作为参数传入Helm:
- 先执行Kustomize构建,提取带哈希后缀的完整ConfigMap名称:
CONFIGMAP_NAME=$(kustomize build | grep -B5 'my-config-path-' | grep 'name:' | awk '{print $2}')
- 执行Helm安装/升级时直接传入该值覆盖对应配置即可:
helm install my-release <第三方Chart地址> --set volumes[0].name=${CONFIGMAP_NAME}
可选方案:关闭ConfigMap哈希后缀
如果你的业务场景不需要Kustomize自动追加哈希后缀,也可以直接关闭该特性,直接用原始名称挂载就不需要做任何替换了:
# 在kustomization.yaml中新增以下配置 generatorOptions: disableNameSuffixHash: true
内容的提问来源于stack exchange,提问作者Charlee Chitsuk
相关产品推荐
相关产品推荐

