为什么这不会改变 Helm 范围循环中变量的值?

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

我有函数:

{{- 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 }}

我用include "myapp.getSubKey" (dict "source" .Values.vars "keys" list(0))

来称呼它

打印出来:

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]]]]

因此您可以看到它在 if 语句中正确向下导航并更改 $map,但是当它退出循环时,它会返回到循环之前的状态。

如何更改“全局”值?

尝试在内部 if-block 中使用运算符 = 而不是赋值运算符 :=。当您将 $map 分配给 := 时,范围仅限于 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 }}

helm v2.13.0 开始支持运算符 =