How to append Secret/ConfigMap hash prefix properly in Helm?

5/28/2020

I want to append the hash of my Secret or ConfigMap contents to the name of the resource in order to trigger a rolling update and keep the old version of that resource around in case there is a mistake in the new configuration.

This can almost be achieved using "helm.sh/resource-policy": keep on the Secret/ConfigMap but these will never be cleaned up. Is there a way of saying 'keep all but the last two' in Helm or an alternative way of achieving this behaviour?

$ helm version
version.BuildInfo{Version:"v3.2.1", GitCommit:"fe51cd1e31e6a202cba7dead9552a6d418ded79a", GitTreeState:"clean", GoVersion:"go1.13.10"}
-- dippynark
kubernetes-helm

1 Answer

5/28/2020

Automatically Roll Deployments

In order to update resource when Secret or Configmap changes, you can add checksum annotation to your deployment

kind: Deployment
spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}

You can revert to your previous configuration with helm rollback command

Update:

A ssuming that your Configmap is generated using values.yaml file, you can add a _helper.tpl function

{{- define "mychart.configmapChecksum" -}}
{{ printf "configmap-%s" (.Values.bar | sha256sum) }}
{{- end }}

And use {{ include "mychart.configmapChecksumed" . }} both as configmap name and reference in deployment.

configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "mychart.configmapChecksumed" . }}
  annotations:
    "helm.sh/resource-policy": keep
data:
  config.properties: |
    foo={{ .Values.bar }}

deployment.yaml

   ...
      volumeMounts:
      - name: config-volume
        mountPath: /etc/config
  volumes:
    - name: config-volume
      configMap:
        # Provide the name of the ConfigMap containing the files you want
        # to add to the container
        name: {{ include "mychart.configmapChecksumed" . }}

Please note that you have to keep "helm.sh/resource-policy": keep annotation on Configmap telling helm to not delete the previous versions.

You can not use {{ include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }} as a configmap name directly because helm rendering will fail with

error calling include: rendering template has a nested reference name
-- edbighead
Source: StackOverflow