在掌舵模板中,我试图通过键检索地图的值。
我尝试从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
答案 0 :(得分:3)
label是一个数组,因此index函数仅适用于整数,这是一个有效的示例:
foolabel: {{ index .Values.label 0 }}
0选择数组的第一个元素。
更好的选择是避免使用数组并将其替换为地图:
label:
foo:
name: foo
value: foo1
bar:
name: bar
value: bar2
您甚至不需要索引功能:
foolabel: {{ .Values.label.foo }}
答案 1 :(得分:1)
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模板./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"
---