templateskubernetes-helmsprig-template-functions

What does the syntax `default (dict) .Values.outer.inner` mean in a helm template?


Given values.yaml:

outer:
  inner: 
    someKey: false

What does the following syntax in a helm template file mean?

  {{- if index (default (dict) .Values.outer.inner) "someKey" }}
  {{- .... }}
  {{- end }}

From context, I can infer what I think it's supposed to do: check if the specified key exists at the specified location.

But where does the default (dict)... syntax come from? Sprig? I can't find it documented in any of these places:

https://v2.helm.sh/docs/chart_template_guide/#template-functions-and-pipelines

https://golang.org/pkg/text/template/#hdr-Functions

http://masterminds.github.io/sprig/

http://masterminds.github.io/sprig/defaults.html

And what does it actually mean?


Solution

  • This particular code avoids a failure if the values outer: {...} doesn't contain an inner key within it.

    dict is a Sprig function that creates a new dictionary. It can be called with any (even) number of parameters; (dict) with no parameters creates an empty dictionary.

    default x y is the same as y | default x and calls the Sprig default function.

    The important thing this is trying to protect against is if .Values.outer doesn't have an inner key within it. If that happened, .Values.outer.inner would be nil, and .Values.outer.inner.someKey would produce an error; the default dict block replaces nil with an empty dictionary, which can be used with index and similar template code.

    I'll often write similar template blocks one layer at a time:

    {{- $outer := .Values.outer | default dict -}}
    {{- $inner := $outer.inner | default dict -}}
    {{- if $inner.someKey }}
    ...
    {{- end }}