Warm tip: This article is reproduced from serverfault.com, please click

How to access individual element from a list inside a helm chart

发布于 2020-11-23 13:17:17

I am trying to access the individual value from an array available in values.yaml file from my helmchart. My values.yaml file content

peer_cidr: 
   - x
   - y
   - z

Accessing from helm chart :

        {{- $dn_count := len .Values.no_of_peers }}
        {{- $end := sub $dn_count 1 }}
        "routes": [
          {{- $root := . -}}
          {{ range $i, $dn := until (atoi (printf "%d" (int64 .Values.no_of_peers))) }}
          { "dst": "{{ index $root "Values" "ipv4_routing" "peer_cidr_list" (printf "%d" ($i) ) }}", "gw": "{{ $root.Values.ipv4_routing.gateway}}"}

With index function iam providing the index but iam facing below error error calling index: cannot index slice/array with type string

Kindly help

Questioner
Balaganesh.V
Viewed
0
David Maze 2020-11-29 05:28:16

You don't need to simulate a C-style for loop in Helm templates. You can directly range over the array and get its contents directly given to the loop body.

{{- $gw := .Values.ipv4_routing.gateway }}
"routes": [
{{- range .Values.ipv4_routing.peer_cidr_list }}
  { "dst": "{{ . }}", "gw": "{{ $gw }}" }
{{- end }}
]

(This will not insert , between JSON array elements as written; you could use $i, $dst := range ... to get the index element as you iterate, or use YAML syntax instead if this context allows it.)

The template code as you've written it has a lot of type conversions between integer and string types; probably most of these are unneeded. The specific error you're getting is because you'r explicitly converting the array index to a string before giving it to index, but the item is an array and uses numeric indexing. Just removing the printf "%d" and atoi calls will probably resolve the issue as well.