helm-template 按键获取地图的值

helm-template get value of the map by key

在 helm-template 中,我试图通过键检索地图的值。

我已经尝试使用 go-templates 中的 index,如下所示: Access a map value using a variable key in a Go template

然而它对我不起作用(见后面的测试)。有替代解决方案的想法吗?

Chart.yaml:

apiVersion: v1
appVersion: "1.0"
description: A Helm chart for Kubernetes
name: foochart
version: 0.1.0

values.yaml:

label:
  - name: foo
    value: foo1
  - name: bar
    value: bar2

templates/test.txt

label: {{ .Values.label }}

适用于 helm template .

---
# Source: foochart/templates/test.txt
label: [map[value:foo1 name:foo] map[name:bar value:bar2]]

但是一旦尝试使用 index:

templates/test.txt

label: {{ .Values.label }}
foolabel: {{ index .Values.label "foo" }}

这行不通 - helm template .:

Error: render error in "foochart/templates/test.txt": template: foochart/templates/test.txt:2:13: executing "foochart/templates/test.txt" at <index .Values.label ...>: error calling index: cannot index slice/array with type string

label 是一个数组,所以 index 函数只能使用整数,这是一个有效的例子:

foolabel: {{ index .Values.label 0 }}

0 选择数组的第一个元素。

更好的选择是避免使用数组并将其替换为映射:

label:
  foo:
    name: foo
    value: foo1
  bar:
    name: bar
    value: bar2

而且你甚至不需要索引函数:

foolabel: {{ .Values.label.foo }}

values.yaml

coins:
  ether:
    host: 10.11.0.50
    port: 123
  btc:
    host: 10.11.0.10
    port: 321
template.yaml
{{- range $key, $val := .Values.coins }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ $key }}
  - env:
    - name: SSH_HOSTNAME
      value: {{ $val.host | quote }}
    - name: SSH_TUNNEL_HOST
      value: {{ $val.port | quote }}
---
{{- end }}

运行 $ 头盔模板 ./helm

---
# Source: test/templates/ether.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: btc
  - env:
    - name: SSH_HOSTNAME
      value: "10.11.0.10"
    - name: SSH_TUNNEL_HOST
      value: "321"
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: ether
  - env:
    - name: SSH_HOSTNAME
      value: "10.11.0.50"
    - name: SSH_TUNNEL_HOST
      value: "123"
---