Search code examples
kubernetes-helmgo-templates

How to use a named template as a YAML list element in a helm chart?


I would like to use a named template as an element of a YAML list.

For example:

I would like to use the following template

{{- define "mytemplate" -}}
name: foo
value: bar
details: baz
{{- end -}}

as an element of the evenmore list:

some:
  more:
    evenmore:
      - name: foo
        value: bar
        details: baz

I tried treating mytemplate explicitly as a list element by changing it to:

{{- define "mytemplate" -}}
- name: foo
  value: bar
  details: baz
{{- end -}}

However, this approach is unusable if I want to use the merge function on mytemplate and some other named template.

I have also tried using the list function:

spec:
  more:
    evenmore:
      {{- include "mytemplate" . | list | toYaml | indent 6 }}

Based on minor modifications, this would leave me with either multiline string as the list element or mismatched indentation for the top field of the list element.

Is there a way to use a named template as a list element without modifying the named template to be a list element itself?


Solution

  • some:
      more:
        evenmore:
          - {{ include "mytemplate" . | indent 8 | trim }}
    

    Breaking apart that last line:

    1. Invoke mytemplate, using the current context as the parameter, but using the Helm include function to get its output as a string.

    2. Indent every line (including the first line) by 8 spaces.

    3. Trim off the leading and trailing whitespace; remove the indentation from the first line.

    So the first line in the template output (the name:) will appear immediately after the hyphen-space YAML list-item marker; and the remaining lines (value: and details:) will be indented 8 spaces, where the number 8 is carefully chosen so they line up in the output.