kuberneteskubernetes-helmgo-templates

How to make nested variables optional in Helm


How do I make an optional block in the values file and then refer to it in the template?

For examples, say I have a values file that looks like the following:

# values.yaml
foo:
   bar: "something"

And then I have a helm template that looks like this:

{{ .Values.foo.bar }}

What if I want to make the foo.bar in the values file optional? An error is raised if the foo key does not exist in the values.

I've tried adding as an if conditional. However, this still fails if the foo key is missing:

{{ if .Values.foo.bar }}
{{ .Values.foo.bar }}
{{ end }}

Solution

  • Most charts will default the parent object to an empty map in values.yaml so it always exists and first level checks {{ if .Values.foo.bar }} will work.

    foo: {}
    

    Test each key in order with parenthesis (added from Torrey's better solution):

    {{ if ((.Values.foo).bar) }}
    bar: {{ .Values.foo.bar }}
    {{ end }}
    

    Use the and function (helm 3.10+/go 1.18+ thanks @nicolauscg)

    {{ if (and .Values.foo .Values.foo.bar) }}
    bar: {{ .Values.foo.bar }}
    {{ end }}
    

    There is also the hasKey function included from sprig if you ever need to check the existence of a falsey or empty value:

    {{ if hasKey .Values.foo "bar" }}