Home > OS >  Helm - Is it possible to add values into a list and then loop over them?
Helm - Is it possible to add values into a list and then loop over them?

Time:06-28

I would like to create a template file which could interact with lists as regular values. Basically, loop over them. So in other words, imagine the following 2 files:

values1.yaml

jobs:
  single: true
  foo: bar
  kek: bor

and

values2.yaml

jobs:
  - foo: bar
    kek: bor
  - foo: rab
    kek: rob

How can I create a template that works on both values files? I personally thought of injecting the first file in a list by doing something like:

{{ if Values.jobs.single }}
    {{ $myList := list .Values.jobs }}
{{ else }}
    {{ $myList := .Values.jobs }}
{{- end }}
{{- range $myList }}
   ...

Unfortunately, this does not seem to work, because assignments are local (so only available within the if-else block).

CodePudding user response:

Helm has a couple of functions that can inspect the type of an object. These generally use the Go terminology, so what you'd normally call a "list" in most languages is a "slice" in Go.

To simplify some issues around variable scoping, I'd also define the variable only once, and use the ternary function to move the conditional inline.

{{- $j := .Values.jobs }}
{{- $myList := kindIs "slice" $j | ternary $j (list $j) }}
{{- range $myList }}...{{ end }}

In a language with more natural support for inline conditionals, this would be the equivalent of

j = values[:jobs]
my_list = if j.is_a?(Array)
          then j
          else [j]
          end
my_list.each {|dict| ...}
  • Related