Search code examples
kuberneteskubernetes-helmgo-templates

Helm range with 2 variables


im trying to a loop with a range in helm but using 2 variables, what i have..

values.yaml

master:
  slave1: 
    - slave1value1
    - slave1value2
  slave2: 
    - slave2value1
    - slave2value2

My actual loop.

{{- range  .Values.master.slave1 }}
        name: http://slave1-{{ . }}
{{- end }}
{{- range  .Values.master.slave2 }}
        name: http://slave2-{{ . }}
{{- end }}

This is actually doing what i need, the output will be like this...

looping on .Values.master.slave1

name: http://slave1-slave1value1
name: http://slave1-slave1value2

looping on .Values.master.slave2

name: http://slave2-slave1value1
name: http://slave2-slave1value2

This is fully working for now, the question is, can i achieve the same result using just one loop block ? i tried this.

{{ alias := .Values.master }}
{{- range  $alias }}
        name: http://{{ . }}-{{ $alias.name }}
{{- end }}

But the output is not what I'm expecting, thanks in advance.


Solution

  • Almost...you need a nested loop to do this. The top-level data structure is a map, where the keys are the worker names and the values are the list of values. So you can iterate through the top-level map, then for each item iterate through the value list.

    {{- $key, $values := range .Values.master -}}
    {{- $value := range $values -}}
    name: http://{{ $key }}-{{ $value }}
    {{ end -}}
    {{- end -}}
    

    Note that we've assigned the values of range to locals to avoid some ambiguity around what exactly . means (inside each range loop it would be the iterator, for the currently-innermost loop).