Search code examples
yamlkubernetes-helmgo-templates

Why doesn't this change the value of the variable in the range loop in Helm?


I have the function:

{{- define "myapp.getSubKey" -}}
  {{- $map := .source }}
  {{ "Before: " }}{{ $map }}
  {{- range $key, $value := .keys }}
    {{- if kindIs "int" $value }}
      {{- $map := index $map (int $value) }}
      {{ "After: " }}{{ $map }}
    {{- end }}
  {{- end }}
  {{ $map }}
{{- end }}

I call it with include "myapp.getSubKey" (dict "source" .Values.vars "keys" list(0))

This prints out:

Before: [map[name:MYSQL_ROOT_PASSWORD valueFrom:map[secretKeyRef:map[key:db-pass name:db-creds]]] map[name:MYSQL_ROOT_USER valueFrom:map[secretKeyRef:map[key:db-user name:db-creds]]]]

After: [map[name:MYSQL_ROOT_PASSWORD valueFrom:map[secretKeyRef:map[key:db-pass name:db-creds]]]

[map[name:MYSQL_ROOT_PASSWORD valueFrom:map[secretKeyRef:map[key:db-pass name:db-creds]]] map[name:MYSQL_ROOT_USER valueFrom:map[secretKeyRef:map[key:db-user name:db-creds]]]]

So you can see it correctly navigates down and changes $map within the if statement, but when it exits the loop, it goes back to what it was before the loop.

How do I change the "global" value?


Solution

  • Try using the operator = instead of assignment operator := in the inner if-block. When you assigned the $map with :=, the scope is limited only to the if-block.

    {{- define "myapp.getSubKey" -}}
      {{- $map := .source }}
      {{ "Before: " }}{{ $map }}
      {{- range $key, $value := .keys }}
        {{- if kindIs "int" $value }}
          {{- $map = index $map (int $value) }} // <------- here
          {{ "After: " }}{{ $map }}
        {{- end }}
      {{- end }}
      {{ $map }}
    {{- end }}
    

    The operator = is supported since helm v2.13.0.