Search code examples
kubernetes-helm

Nested default value in a helm chart


I have the following bloc in a helm chart:

value: {{.Values.service.container.SubBloc.myKey |  default "mydefault"  }}

The default works well if in my value file I define a SubBloc but not my "mykey", like this:

service:
  container:
    SubBloc: 
      Key2: Value2
    resources:
      ...
    

However, if I did not define SubBloc at all, like here:

service:
  container:
    resources:
      ...

Then helm chart is not parsable.

Is there a way to parse "default nested value"?


Solution

  • At a code level, a field lookup a.b is valid if a is a dictionary (even if it doesn't contain b), but not if a is nil. A technique I find useful here is to set a variable that should contain the parent dictionary, but uses default on the parent to ensure it's never nil:

    {{- $subBloc := .Values.service.container.SubBloc | default dict }}
    value: {{ $subBloc.myKey |  default "mydefault" }}
    

    If the upper layers could also be absent, you'd need to repeat this technique for each layer of the value tree. It's usually safe to assume anything that's in the chart's values.yaml is present (though things can be explicitly overridden to be nil). It can be helpful to design your charts to have shallower values trees to simplify this setup.