Search code examples
loopskuberneteskubernetes-helmconfigmapkubernetes-secrets

Helm mount a set of confimaps or secrets dynamically


I have a use case for a helm deployment to mount a set of configmaps (it can be also secrets) which are present in the system already.

The configmaps follow a pattern *-version. As the name suggests, this contains version details of each application we have in the namespace. With this new deployment mounting all these configmaps, I can run a Prometheus exporter in there to scrape this information and send it to Prometheus.

I'm not sure if Helm can do this dynamically with a given pattern and loop somehow to form all the configmap mount to different files in the pod.

Optionally, I can define this configmap names in the values.yaml and also loop through it, but it would be bit difficult to maintain and to update values when there is new deployment added.


Solution

  • In principle you can use the Helm lookup function for this. It might look something like

    {{- $lookups := lookup "v1" "ConfigMap" .Release.Namespace "" }}
    volumes:
    {{- range $lookups.items }}
    {{- if hasSuffix "-version" .metadata.name }}
      - name: {{ .metadata.name }}
        configMap:
          name: {{ .metadata.name }}
    {{- end }}
    {{- end }}
    containers:
      - ...
        volumeMounts:
    {{- range $lookups.items }}
    {{- if hasSuffix "-version" .metadata.name }}
          - name: {{ .metadata.name }}
            mountPath: /tmp/{{ .metadata.name }}
            subPath: version
    {{- end }}
    {{- end }}
    

    Note that this will not automatically update itself; you will need to helm upgrade the chart whenever the set of resources in the cluster changes. Its behavior also depends heavily on what's in the cluster, which can make this hard to test. But this is the only way to do this using only Helm.