kuberneteskubernetes-helmconfigmapgitops

Helm tpl function in configmap failing to parse yaml file content


I have an application that needs to read a number of YAML files from a given path.

This path is populated via a K8s ConfigMap that is templated via Helm to fetch all files base-yaml from a config directory and has to apply the tpl function in each of them to fill them with application-specific information.

The structure is as follows: I have in my gitops repo a directory config with file_1.yaml and file_2.yaml The content of the file_1.yaml is something like:

block_1:
  my_var: "{{ .Values.my_var }}"
  something: "something"
block_2:
  aws_region: "{{ .Values.aws_region}}"
block_3:
  my_composite_var: "fixed_prefix-{{ .Values.moving_prefix }}-{{ .Values.some_value }}"
  complex_json: "...[some complex entry with escaped quotes etc]"

I created a config map helm template as follow to list any file in the config directory:

apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ .Values.configMapName }}
  labels:
    app: {{ .Release.Name }}
data:
{{- $files := .Files.Glob (printf "%s/*" .Values.dirName) }}
{{- range $path, $file := $files }}
  {{ base $path }}: |
{{ $file | toString | indent 4 }}
{{- end }}

Up to here it works, but I didn't apply any template, and the mapped files in my pod will be the verbatim content of the yaml files. The moment in which I replace {{ $file | toString | indent 4 }} with anything that applies tpl then issues arise:

{{ tpl ($file | toString) . | indent 4 }} => Error template: gotpl:9: bad character U+002D '-'

I tried several combination (such as {{ tpl (quote $file | toString) . | indent 4 }} or even {{ tpl (b64enc $file | toString) . | b64dec | indent 4 }}) but I never got out of that error.

Any help?


Solution

  • I found the issue.

    This is how I finally made it work as I expected:

    apiVersion: v1
    kind: ConfigMap
    metadata:
      name: {{ .Values.configMapName }}
      labels:
        app: {{ .Release.Name }}
    data:
    {{- range $path, $bytes := .Files.Glob "config/*.yaml" }}
      {{ base $path }}: |
    {{ tpl (toString $bytes | indent 2) $ | indent 4 }}
    {{- end }}
    

    The trick is in the range before the .Files.Glob, and the toString of the file value (as Glob returns a byte array).