How to read a value from json through Helm charts

12/20/2018

I have defined value in a json file.

cat templates/encrypt.json
{"encrypt": "cg8StVXbQJ0gPvMd9o7yrg=="}

The value has to be passed to the yaml file as below

-config-file={{ tpl (.Files.Get "encrypt.json") . | b64enc }}  \

Below is the helm chart snippet

exec /bin/consul agent \
            -node="${NODE}" \
            -advertise="${POD_IP}" \
            -bind=0.0.0.0 \
            -client=0.0.0.0 \
            {{- if .Values.client.grpc }}
            -hcl="ports { grpc = 8502 }" \
            {{- end }}
            -config-dir=/consul/config \
            {{- range .Values.client.extraVolumes }}
            {{- if .load }}
            -config-dir=/consul/userconfig/{{ .name }} \
            {{- end }}
            {{- end }}
            -datacenter={{ .Values.global.datacenter }} \
            -data-dir=/consul/data \
            -config-file={{ tpl (.Files.Get "encrypt.json") . | b64enc }}  \
            {{- if (.Values.client.join) and (gt (len .Values.client.join) 0) }}

When I run my health charts, I get the below error.

Error: unable to decode "": Object 'Kind' is missing in '{"encrypt":"cg8StVXbQJ0gPvMd9o7yrg=="}'
-- Sunil Gajula
kubernetes
kubernetes-helm

1 Answer

12/20/2018

What you're injecting with {{ tpl (.Files.Get "encrypt.json") . | b64enc }} is the content of the json i.e. {"encrypt": "cg8StVXbQJ0gPvMd9o7yrg=="}. But I don't think that is what that parameter expects. It seems to expect a filename for a file that should be available in the Pod, which can be done by mounting the configmap. That is how the consul helm chart in the official kubernetes charts handles it:

            {{- if .Values.Gossip.Encrypt }}
            if [ -e /etc/consul/secrets/gossip-key ]; then
              echo "{\"encrypt\": \"$(base64 /etc/consul/secrets/gossip-key)\"}" > /etc/consul/encrypt.json
              GOSSIP_KEY="-config-file /etc/consul/encrypt.json"
            fi
            {{- end }}

It lets the user set a gossip key in the values file and sets that in a secret which is mounted into the Pods as a volume. I'd suggest following the approach of that chart if you can.

I guess what you are doing is building on top of the consul helm chart that Hashicorp provides as the code you include is similar to that. So presumably you can't use the one from the kubernetes repo but you should be able to follow the approach taken by that chart for this config file.

-- Ryan Dawson
Source: StackOverflow