Search code examples
kubernetes-helmgo-templates

How to render list (slice) of string as list in yaml file by Helm Chart


I have a list or (slice) of string data for example [string1, string2, string3]. I want to render it in list fashion in yaml file as

- string1
- string2
- string3

How can I do that?

I have tried

{{- range $val := $list }}
  - {{ $val }}
{{- end }}

but it renders following as multiple line of strings

- |-
   - string1
   - string2
   - string2

any idea? thank you in advance


Solution

  • You may use formatted string output to solve the problem.

    eg.

    values.yaml

    arr:
      - string1
      - string2
      - string3
    

    _helpers.tpl

    {{/*
    Print string from list split by ,
    */}}
    {{- define "print.list" -}}
    {{- range $idx, $val := $.Values.arr -}}
    {{- if $idx }}
    {{- print ", "  -}} 
    {{- end -}}
    {{- $val -}}
    {{- end -}}
    {{- end -}}
    

    The template you want to render, for example comfigmap.yaml

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: {{ include "test.fullname" . }}
    data:
      test: [{{- include "print.list" .}}]
    

    output

    piVersion: v1
    kind: ConfigMap
    metadata:
      name: test
    data:
      test: [string1, string2, string3]
    

    ---↓ 2022-01-05 update ↓---

    values.yaml

    arr:
      - string1
      - string2
      - string3
    

    The template you want to render, for example comfigmap.yaml

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: {{ include "test.fullname" . }}
    data:
      test: |
        {{- toYaml $.Values.arr | nindent 4 }}
    

    output

    piVersion: v1
    kind: ConfigMap
    metadata:
      name: test
    data:
      test: |
        - string1
        - string2
        - string3
    

    no pipe

    helm --dry-run --debug template test .

    The template you want to render, for example comfigmap.yaml

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: {{ include "test.fullname" . }}
    data:
      test: 
        {{- toYaml $.Values.arr | nindent 4 }}
    

    output

    piVersion: v1
    kind: ConfigMap
    metadata:
      name: test
    data:
      test: 
        - string1
        - string2
        - string3
    

    range

    {{- range $i, $v := $.Values.arr }}
    - {{ $v }}
    {{- end }}
    

    output

    - string1
    - string2
    - string3