子Chart中ConfigMap变更触发K8s Deployment重启及父模板扩展方案
解决方案
针对问题1:给父Chart预留注解扩展点
让基础Chart的deployment.yaml支持通过values传入额外注解,这样子Chart就能把自己的配置哈希注入进去:
- 修改基础Chart的
deployment.yaml:
spec: template: metadata: annotations: # 保留原有注解 {{- if .Values.deployment.extraAnnotations }} {{- toYaml .Values.deployment.extraAnnotations | nindent 8 }} {{- end }}
- 在子Chart的values文件(或者部署时的自定义values)中,计算自身配置文件的哈希并传入:
deployment: extraAnnotations: checksum/config: {{ .Files.Glob "config/*" | sha256sum }}
这样子Chart就能把自己的配置哈希加到父Chart的Deployment注解里,配置变更时自动触发重启。
针对问题2:更优的Helm原生方案
方案1:用tpl函数动态执行子Chart模板
在基础Chart的deployment.yaml中,用tpl函数允许子Chart传入模板片段,在子Chart上下文执行计算:
spec: template: metadata: annotations: checksum/config: {{ tpl .Values.configHashTemplate . }}
然后子Chart的values中传入模板字符串:
configHashTemplate: '{{ .Files.Glob "config/*" | sha256sum }}'
tpl会在子Chart的上下文里执行这个模板,算出正确的配置哈希,完全用Helm原生机制实现,不需要外部工具。
方案2:利用ConfigMap的自动哈希关联
子Chart把配置文件生成ConfigMap,然后父Chart的Deployment引用这个ConfigMap的哈希,配置变更时ConfigMap更新,触发Deployment重启:
- 子Chart中定义ConfigMap(比如
templates/configmap.yaml):
apiVersion: v1 kind: ConfigMap metadata: name: my-service-config data: {{- (.Files.Glob "config/*").AsConfig | nindent 2 }}
- 子Chart在
_helpers.tpl中添加哈希计算模板:
{{- define "my-service.configmap.checksum" -}} {{- include "my-service.configmap" . | sha256sum -}} {{- end -}} {{- define "my-service.configmap" -}} apiVersion: v1 kind: ConfigMap metadata: name: my-service-config data: {{- (.Files.Glob "config/*").AsConfig | nindent 2 }} {{- end -}}
- 基础Chart的
deployment.yaml中引用这个哈希:
spec: template: metadata: annotations: checksum/config: {{ include "my-service.configmap.checksum" . }} volumes: - name: config configMap: name: my-service-config
这种方式完全依赖Helm的模板渲染机制,配置文件变更时ConfigMap内容更新,哈希值随之变化,自动触发Deployment滚动更新,是最符合Helm设计的方案。
内容的提问来源于stack exchange,提问作者Artem Ptushkin
相关产品推荐
相关产品推荐

