helm function to transform yaml to property-like format

Viewed 18

new to k8s, trying to remove stupid boilerplate and write better config-map.yaml generation. Expected format is:

...
data:
  first.property: 1
  second.property: 2
...

I don't want to refer there key by key to values.yaml, like:

...
data:
  first.property: {{.Values.configuration.first.property}}
  second.property: {{.Values.configuration.second.property}}
  ...

I want to include whole subtree into here, like:

{{  (toYaml .Values.configuration | indent 2)  }}

That works, but (as expected) the yaml is inserted as is. I need to adapt it to property-like format. So the question is: is there a function/way in helm/go templates how to transform this yaml:

a:
  b:
    c: 1
    d: 2

into following representation?

a.b.c: 1
a.b.d: 2
1 Answers

this based on answer How do you apply a recursive formatting with Go Templates (Helm)? in which I fixed some problems and the final solution could be:

{{- define "flattenYaml" -}}
{{- $dict := . -}}
{{- $prefix := $dict.prefix -}}
{{- $data := $dict.data -}}
{{- $knd := kindOf $data -}}
    {{- if eq $knd "map" }}
        {{- range (keys $data) }}
            {{- $key := . }}
            {{- $prefixedKey := (printf "%s.%s" $prefix $key) }}
            {{- $value := get $data $key }}
            {{- $valueKind := kindOf $value }}
            {{- if eq $valueKind "map" }}
                {{-   include "flattenYaml" (dict "prefix" ($prefixedKey) "data" $value) }}
            {{- else }}
                {{-   printf "%s=%s\n" $prefixedKey (toJson $value) }}
            {{- end }}
        {{- end }}
    {{- else }}
        {{ toJson . }}#k({{ $knd }})
    {{- end }}
{{- end -}}

for more details see my answer there.

Related