How to create template in the helm chart?

11/15/2021

I need to create template for secret value.

This is the secret file:

apiVersion: v1
kind: Secret
metadata:
  name: secret
type: Opaque
stringData:
  "user":  "user"
  "password":  "password"

And this is what I have created in the _helpers.tpl

{{/*
  User
*/}}
{{- define "@@chartName@@.user" -}}
{{- $secret := lookup "v1" "Secret" .Release.Namespace "secret" -}}
  {{- if $secret -}}
     {{- print $secret.stringData.user}}
  {{- else -}}
     {{- fail "The secret is absent" -}}
  {{- end -}}
{{- end -}}

But it doesn't work and I get the error : <$secret.stringData.user>: nil pointer evaluating interface {}.user

I have created the secret before installation helm chart and I don't know what is the reason of this error. Thanks for any help!

-- Java
kubernetes
kubernetes-helm
kubernetes-secrets

1 Answer

11/15/2021

You will get that error if $secret exists, but doesn't contain stringData.

At a Helm level, you can work around this by using the default function to force it to exist ("doesn't have stringData" and "doesn't have user" are approximately the same error):

{{- $secret := lookup "v1" "Secret" .Release.Namespace "secret" | default dict -}}
{{- $stringData := $secret.stringData | default dict -}}
{{- $stringData.user | required "The secret is absent" -}}

At a higher-level, if it's possible to read back the Secret, it probably only has the base64-encoded data field (even if it was created with stringData). Helm provides a b64dec function that could decode it. It'd be better to refer to the secret as an environment variable in your pod spec, or pass the value directly into Helm.

# in a Pod spec; without using Helm `lookup`
env:
  - name: USER
    valueFrom:
      secretKeyRef:
        name: secret
        key: user
# or passed directly via Helm
{{- $credentials := .Values.credentials | default dict -}}
{{- $credentials.user | required "missing user.credentials" -}}
-- David Maze
Source: StackOverflow