I have a few YAML files in my chart directory and, in my template, I want use their contents in an array. For example, if I had 2 files:
# file-a.yaml:
name: abc
# file-b.yaml:
name: xyz
And my template:
{{ printf "files:" | nindent 8 -}}
{{- range $stagesPath, $fileContent := $.Files.Glob (printf "files/*.yaml") }}
- {{ $.Files.Get $stagesPath | toYaml | nindent 10 }}
{{- end }}
would render:
files:
-
|
name: abc
-
|
name: xyz
But I want:
files:
- name: abc
- name: xyz
Can you please help me? :)
.Files.Get
already returns a string. When you pipe it through toYaml
, the string winds up double-escaped. That might be why you're winding up with YAML block-scalar syntax.
Since you already have the file content as a string, you don't need toYaml
. You do need to indent
it to fit correctly in the containing YAML block syntax, but then trim
the leading whitespace so the first line isn't over-indented.
files:
{{- range $stagesPath := $.Files.Glob (printf "files/*.yaml") }}
- {{ $.Files.Get $stagesPath | indent 10 | trim }}
{{- end }}
In principle you could use fromYaml
to parse the file content into a structured value. The templating language doesn't have any sort of map
function, so building a list of data values and then dumping it out is tricky. This probably works (reading each file, parsing it fromYaml
, collecting each item into a list, and then putting the whole list through toYaml
once):
{{- $files := list }}
{{- range $stagesPath := .Files.Glob "files/*.yaml" }}
{{- $files = append $files ($.Files.Get $stagesPath | fromYaml) }}
{{- end }}
files: {{- $files | toYaml | nindent 10 }}