如何在Helm中实现ConfigMap多目标文件夹的动态挂载?
Helm动态挂载ConfigMap配置的实现方案
方案核心思路
利用Helm内置的.Files.Glob方法遍历指定目录下的所有模板文件,自动生成ConfigMap配置项和对应的挂载规则,无需手动新增配置。
实现步骤
第一步:自动生成ConfigMap配置
替换原有手动编写data字段的逻辑,自动遍历两个目录的模板文件生成配置项:
kind: ConfigMap apiVersion: v1 metadata: name: config data: {{- /* 遍历configuration目录下所有.tpl文件,生成对应配置项 */}} {{- range $path, $_ := .Files.Glob "configuration/*.tpl" }} {{- $fileName := base $path | replace ".tpl" ".xml" }} config-{{ $fileName }}: | {{ $.Files.Get $path | indent 4 }} {{- end }} {{- /* 遍历controlsets目录下所有.tpl文件,生成对应配置项 */}} {{- range $path, $_ := .Files.Glob "controlsets/*.tpl" }} {{- $fileName := base $path | replace ".tpl" ".xml" }} control-{{ $fileName }}: | {{ $.Files.Get $path | indent 4 }} {{- end }}
第二步:动态生成挂载规则
根据容器目录的实际情况选择对应方案:
场景1:容器内/app目录无需要保留的原有文件
可以直接调整ConfigMap的key为容器内相对路径,仅需1行挂载配置即可自动匹配目录:
调整后ConfigMap的data逻辑:
data: {{- /* 遍历configuration目录,key设置为容器内相对路径 */}} {{- range $path, $_ := .Files.Glob "configuration/*.tpl" }} {{- $fileName := base $path | replace ".tpl" ".xml" }} Configuration/{{ $fileName }}: | {{ $.Files.Get $path | indent 4 }} {{- end }} {{- /* 遍历controlsets目录,key设置为容器内相对路径 */}} {{- range $path, $_ := .Files.Glob "controlsets/*.tpl" }} {{- $fileName := base $path | replace ".tpl" ".xml" }} Controlsets/{{ $fileName }}: | {{ $.Files.Get $path | indent 4 }} {{- end }}
对应volumeMounts配置:
volumeMounts: - name: config-volume mountPath: /app
场景2:容器内/app目录存在需保留的原有文件
通过range动态生成每个配置的subPath挂载规则,避免覆盖目录原有内容:
volumeMounts: {{- /* 遍历configuration目录生成挂载规则 */}} {{- range $path, $_ := .Files.Glob "configuration/*.tpl" }} {{- $fileName := base $path | replace ".tpl" ".xml" }} - name: config-volume mountPath: /app/Configuration/{{ $fileName }} subPath: config-{{ $fileName }} {{- end }} {{- /* 遍历controlsets目录生成挂载规则 */}} {{- range $path, $_ := .Files.Glob "controlsets/*.tpl" }} {{- $fileName := base $path | replace ".tpl" ".xml" }} - name: config-volume mountPath: /app/Controlsets/{{ $fileName }} subPath: control-{{ $fileName }} {{- end }}
注意事项
configuration、controlsets目录需要放在Helm Chart的根目录下(与Chart.yaml、templates目录同级),否则.Files无法读取对应文件。- 新增配置文件时仅需将对应
.tpl文件放入对应目录即可,无需修改任何YAML配置,Helm会自动识别生成对应资源。
内容的提问来源于stack exchange,提问作者trubar
相关产品推荐
相关产品推荐

