Search code examples
kuberneteskubernetes-helmconfigmap

How can I use a json file in my configmap.yaml (Helm)?


I am using Helm to deploy to a Kubernetes cluster. I have researched configmaps and found it is possible to retrieve data from a file and put it into the configmap.

I have the following configmap.yaml:

kind: ConfigMap 
apiVersion: v1 
metadata:
  name: {{ .Values.app.configMap }}
  namespace: {{ .Values.app.namespace }}
data:
    config.json: |-
      {{ .Files.Glob "my-config.json" | indent 2}}

and my deployment.yaml contains the relevant volumeMount (if I put actual json data directly into configmap.yaml then the config deploys). My configmap.yaml and deployment.yaml are both kept in /chart/templates but I keep my-config.json within the base helm chart directory, outside of the templates folder.

When I try deploying with the chart, I get the following error:

Error: template: chart/templates/configmap.yaml:8:54: executing "chart/templates/configmap.yaml" at <2>: wrong type for value; expected string; got engine.files

How can I use the .json file in my configmap without putting the raw json data directly into the yaml file?


Solution

  • The .Files object is described in the Helm Built-in Objects documentation. .Files.Glob returns a list of files matching some pattern, like *.json; you probably want .Files.Get instead to return the file content.

    YAML is also very sensitive to whitespace handling and indentation. When you do retrieve the file, you probably want that line to start at the first column, but then call the indent function with some number more than the indent level of the previous line. This also indents the first line, and you can double-check with helm template that the right thing came out.

    data:
      {{-/* Note, indent of only two spaces */}}
      config.json: |-
    {{ .Files.Get "my-config.json" | indent 4 }}
    {{/* .Get, not .Glob; indent 4 spaces, more than 2 above */}}