kuberneteskubernetes-helmsprig-template-functions

Helm templating: index for subkeys


I'd like to impement the following scenario.

Global variable

global:
  env:
    name: prod

Chart specific variable

env:
  name: dev

I want to have precedence of chart specific > global variable

eg: In my chart, I want to use something like

      containers:
          - name: "{{- include "tester.getValueWithPrecedence" (list . "env.name") -}}"

And this is the _helpers.tpl function

{{- define "tester.getValueWithPrecedence" -}}
{{- $top := index . 0 }}
{{- $var := index . 1 }}
{{- if hasKey $top.Values $var -}}
{{- index $top.Values $var -}}
{{- else if hasKey $top.Values.global $var -}}
{{- index $top.Values.global $var -}}
{{- end -}}
{{- end -}}

I think the problem is env.name key is not interpreted as subkey, but a string.

Is there any way to achieve this?

Any help is much appreciated.


Solution

  • I figured out a simpler approach.

    {{/* Define getmethekey function */}}
    {{- define "tester.getmethekey" -}}
    {{- $root := first . -}}
    {{- $keys := rest . -}}
    {{- $value := $root.Values -}}
    
    {{- range $index, $key := $keys -}}
      {{- if kindIs "map" $value -}}
        {{- if hasKey $value $key -}}
          {{- $value = index $value $key -}}
        {{- else -}}
          {{- $value = "" -}}
        {{- end -}}
      {{- else -}}
        {{- $value = "" -}}
      {{- end -}}
    {{- end -}}
    
    {{- $value -}}
    {{- end -}}
    

    and the input will be

              - name: "{{- include "tester.getmethekey" (list . "env" "name") -}}"
    

    Values.yaml

    env:
      name: rajesh