helm-template get value of the map by key
Asked Answered
I

2

23

In the helm-template I'm trying to retrieve a value of the map by key.

I've tried to use the index from the go-templates, as suggested here: Access a map value using a variable key in a Go template

However it doesn't work for me (see later test). Any idea for the alternative solution?

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

Works OK for helm template .:

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

However once trying to use the index:

templates/test.txt

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

It won't work - 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
Impregnate answered 13/10, 2018 at 10:44 Comment(0)
C
21

label is an array, so the index function will only work with integers, this is a working example:

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

The 0 selects the first element of the array.

A better option is to avoid using an array and replace it with a map:

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

And you dont even need the index function:

foolabel: {{ .Values.label.foo }}
Cheiron answered 13/10, 2018 at 17:10 Comment(2)
What wold be the correct syntax if I want to pass the map index programmatically? I know this is wrong, but to give you an idea, {{ .Values.label.{{ .Values.mapIndex }} }}, and use helm install --set mapIndex=foo ...Busywork
@ChrisF, foolabel: {{ get .Values.label .Values.mapIndex }}. See https://mcmap.net/q/585253/-helm-get-value-from-a-map-where-the-key-is-variableKaddish
M
18

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

run $ helm template ./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"
---
Matthiew answered 5/11, 2019 at 15:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.