Search code examples
kubernetes-helmhelm3

How do I use toyaml with a default empty/null value?


I really want to avoid an "if" condition because this feels like something that could be handled in a more readable way.

I have a value like this:

healthChecks:
  livenessProbe:
    httpGet:
      path: /
      port: http

And use it like this:

{{- toYaml .Values.healthChecks | nindent 10 }}

But the value might be empty and I want to support that. So if the value healthChecks: isn't specified the chart doesn't render it. How do I do this?

I was hoping toYaml would be smart enough to see .Values.healthChecks is empty and not do anything but it throws an error: unable to parse YAML: error converting YAML to JSON: yaml: line X: could not find expected ':'

Do I seriously need an if condition for this? Is there a built in way to just have toYaml do nothing if a value is empty?


Solution

  • If you really want to avoid a conditional, you can use default to provide some sort of default value that can get rendered. For example, using dict to produce an empty dictionary should render to {} inside the template.

            healthChecks:
    {{ .Values.healthChecks | default dict | toYaml | indent 10 }}
    

    I probably would use a conditional here, which will have the particular advantage that you can avoid emitting the key if the value isn't present. Using with instead of if will also mean you don't need to repeat the value (but has the downside that it changes the meaning of ., if you need to refer to other top-level values).

    {{ with .Values.healthChecks }}
            healthChecks: {{- toYaml . | nindent 10 }}
    {{- end }}