如何在 helm 模板中访问超出当前范围控制的变量

How to access variable out of current range control in helm template

我有这样的 helm 模板,

1  {{- range $device_type := include "example.supportedDevices" . }}
3  {{- $total_worker_sets := get $.Values.all_worker_sets $device_type }}
4  {{- range $item := $total_worker_sets }}
5  {{- if eq $device_type "cpu" }}
6  {{- $type := "cpu" }}
7  {{- else }}
8  {{- $type := $item.name }}
9  {{- end }}
10  {{- range $i, $e := until ($item.worker_sets|int) }}
11  ---
12  apiVersion: apps/v1
13  kind: StatefulSet
14  metadata:
15    name: {{ template "example.fullname" $ }}-worker-{{ $type }}-{{ $i }}
16  spec:
...
{{- end }}
{{- end }}
{{- end }}

helm lintreturns: [错误] 模板/:解析错误 (example/templates/worker.yaml:15):未定义的变量“$type”

您可以使用 $ 到达根范围。因此,您可以使用 $.type 而不是 .type。在这里你使用了 $type,这就是为什么它显示未定义(undefined variable "$type",而是 $.type.

当您在 if-block 内分配 $type:= 时,范围仅限于 if-block。在 if-block 之外定义变量,以便以后使用。

1  {{- range $device_type := include "example.supportedDevices" . }}
3  {{- $total_worker_sets := get $.Values.all_worker_sets $device_type }}
x  {{- $type := "" }}   ### <----define here
4  {{- range $item := $total_worker_sets }}
5  {{- if eq $device_type "cpu" }}
6  {{- $type = "cpu" }}  ### <--- replace :=  with = to avoid re-declaration
7  {{- else }}
8  {{- $type = $item.name }} ### <--- replace :=  with =
9  {{- end }}
10  {{- range $i, $e := until ($item.worker_sets|int) }}
11  ---
12  apiVersion: apps/v1
13  kind: StatefulSet
14  metadata:
15    name: {{ template "example.fullname" $ }}-worker-{{ $type }}-{{ $i }}
16  spec:
...
{{- end }}
{{- end }}
{{- end }}

正如@KamolHasan 在, if you try to define a variable inside an {{ if }}...{{ end }} block, the scope of the variable is that block. Helm (and more specifically the Sprig extension template library) provides a ternary 扩展函数中指出的那样解决这个问题。

ternary 接受三个参数;按顺序,真值、假值和条件。这种特定的顺序让您可以使用模板管道语法来提供条件。它在本质上类似于 C 类语言中的 ? : 内联条件运算符

{{ $value := ternary "if-true" "if-false" $condition }}
const char *value = condition ? "if-true" : "if-false";

这会让你提升 $type 出条件块

{{- range $item := $total_worker_sets }}
{{- $type := eq $device_type "cpu" | ternary "cpu" $item.name }}
{{- range $i, $e := until ($item.worker_sets|int) }}
name: {{ template "example.fullname" $ }}-worker-{{ $type }}-{{ $i }}
{{- end }}
{{- end }}