【问题标题】:helm-template get value of the map by keyhelm-template 按键获取地图的值
【发布时间】:2018-10-13 10:44:01
【问题描述】:

在 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

【问题讨论】:

    标签: kubernetes-helm


    【解决方案1】:

    label 是一个数组,因此索引函数只能处理整数,这是一个工作示例:

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

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

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

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

    而且你甚至不需要索引功能:

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

    【讨论】:

    • 这里为什么需要索引?你就不能.Values.label.foo吗?
    • 你说得对,第二个选项不需要索引
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-08-16
      • 2022-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 2013-05-20
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多