Insert multiline json string into helm template for base64 encoding

Steve picture Steve · Jan 11, 2019 · Viewed 21.2k times · Source

I am trying to insert multiline json string into helm template for base64 encoding required for Kubernetes secret.

Goals:

  • helm value is injected into json string
  • multi-line json string must be base64 encoded using b64enc

myfile1.json does not work but myfile2.json works. I prefer not to put entire json file in values.yaml.

apiVersion: v1
kind: Secret
metadata:
  name: {{ template "mychart.fullname" . }}
  labels:
    app: {{ template "mychart.name" . }}
    chart: {{ template "mychart.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
type: Opaque
data:
  myfile.json: {{ |-
    {
      "item1": {
          "name": "{{ .Values.item1.name }}"
      },
      "item2": {
      }
    } | b64enc }}
  myfile2.json: {{ .Values.myfile2 | b64enc }}

Answer

Technetium picture Technetium · Nov 27, 2019

You actually don't need to base64-encode the secret in the helm chart. If you use the stringData field instead of data field, Kubernetes knows that it needs to base64 encode the data upon the secret's deployment.

From the docs (Source):

The Secret contains two maps: data and stringData. The data field is used to store arbitrary data, encoded using base64. The stringData field is provided for convenience, and allows you to provide secret data as unencoded strings.

So we can rewrite your secret using stringData instead of data and keep multiline json strings in templates like so:

apiVersion: "v1"
kind: "Secret"
metadata:
  name: {{ template "mychart.fullname" . }}
  labels:
    app: {{ template "mychart.name" . }}
    chart: {{ template "mychart.chart" . }}
    release: {{ .Release.Name }}
    heritage: {{ .Release.Service }}
type: "Opaque"
stringData:
  myfile.json: |-
    {
      "item1": {
          "name": "{{ .Values.item1.name }}"
      },
      "item2": {
      }
    }
  myfile2.json: {{ .Values.myfile2 }}

Note that this does not mean you suddenly need to worry about having unencoded secrets. stringData will ultimately be base64-encoded and converted to data when it is installed, so it will behave exactly the same once it's loaded into Kubernetes.

Again, from the docs (emphasis mine) (Source):

stringData allows specifying non-binary secret data in string form. It is provided as a write-only convenience method. All keys and values are merged into the data field on write, overwriting any existing values. It is never output when reading from the API.