helm or operator with required function

Viewed 86

I have to check for mandatory values based on some condition.
My values.yaml is as below

id: 3
test:
 id: 2
 test1:
  id: 1

In my template, I need to check if id is present at .Values.test.test1.id and assign that value. If not fall back to .Values.test.id and at last .Values.id. But id has to be mandatory and I need to use required function.

My template is as below

{{- if .Values.test.test1.id }}
<assign> {{ .Values.test.test1.id }}
{{- else }}
{{- $id := .Values.test.id }}
{{- $id2 := .Values.id }}
<assign> <need to check required with or of $id $id2> </assign>
{{- end }}

I know this can be solved with one elseif in between if and else. But I need to repeat the same logic for many ids.
What is the best way to achieve this?

1 Answers

It seems like a perfect fit for the coalesce function, which

takes a list of values and returns the first non-empty one.

Source: https://helm.sh/docs/chart_template_guide/function_list/#coalesce

You will also need to use the default function to convert the cases when the test or test.test1 dictionaries are not defined.

All this together, gives:

{{- $test := .Values.test | default dict -}}
{{- $test1 := $test.test1 | default dict -}}
{{- $id := required "Please provide an ID" (
  coalesce $test1.id $test.id .Values.id
) -}}
id: {{ $id }}

And here are the test cases and results:

  • Gives:
    id: 1
    
    when values.yaml is
    id: 3
    test:
      id: 2
      test1:
        id: 1
    
  • Gives:
    id: 2
    
    when values.yaml is
    id: 3
    test:
      id: 2
    
  • Gives:
    id: 3
    
    when values.yaml is
    id: 3
    
  • Gives:
    Error: execution error at (demo/templates/test.yaml:3:11): 
      Please provide an ID
    
    when values.yaml is an empty file
Related