Helm template need to get and set value in dict

Viewed 116

I have the following data in my function $newdict

   modules:
     module1: 
      enabled: true
     module2:
      enabled: false
     module3:
      enabled: true, etc

What is need to do is : check if module1 enabled, then set enabled for module2 as well. What I tried in _helpers.tpl file:

  {{- range $key, $value := $newdict -}}
  {{ if and (eq $key "module1") (eq "enabled" "true") }}
  {{ $_ := set $newdict $key "module2" (eq "enabled" "true") }} 
  {{ end }}  
  {{ end }}
  {{ toYaml $newdict }}

helm lint doesn't show any errors, but the changes are not reflected in $newdict

This thing is needed for deployment.yaml to deploy init container:

     initContainers:
  {{- $mycustom := (include "myfunction" . ) | fromYaml}}
  {{- range $key, $value := $mycustom }}
    {{- if $value.enabled }}
    - name: init-{{ $key }}-myinit

So, in the end, I need to deploy init container "module2" only if "module1" is also deployed

1 Answers

Helm's general style is that values are immutable. I'd avoid the set function here and stick to a more functional style.

It may help your setup that you can directly index things in dict (map) structures, or use the standard Go template index function. You don't need to iterate through the entire dict looking for a key. So if you're sure the variable has keys module1 and module2 then you can simplify the final logic to:

initContainers:
{{- if or .Values.module1.enabled .Values.module2.enabled }}
  - name: init-module2-myinit
  ...
{{- end }}

Your setup hints at having more init containers; module1, module2, and module3 would each have their own init containers, but you also want to emit module2's whenever module1 is turned on regardless of the module2 setting. One way to approach this might be to write a helper function that decided whether a given module was enabled:

{{/* Decide whether some module is enabled.  Call with a list of
     two items, the values structure to examine and the specific
     module key.  Returns either the string "true" or an empty
     string. */}}
{{- define "is-module-enabled" -}}
{{- $modules := index . 0 -}}
{{- $key := index . 1 -}}
{{- if index $modules $key "enabled" -}}
true
{{- else if and (eq $key "module2") $modules.module1.enabled -}}
true
{{- end -}}
{{- end -}}
initContainers:
{{- range $key := .Values.modules -}}
{{- if include "is-module-enabled" (list .Values.modules $key) }}
  - name: init-{{ $key }}-myinit
  ...
{{- end }}
{{- end }}
Related