I have the following yaml
items:
- itemName: a
awesome: true
- itemName: b
- itemName: c
awesome: false
I need a function that gets a
as an output, since item a
has the attribute awesome == true
. How do I do that?
Approach that does not work:
{{- $result := "nope" }}
{{- range $i := $items }}
{{- if and (and (hasKey $i. awesome) ($i.awesome)) !($result -eq "nope") }}
{{- $result := $i.itemName }}
{{- end }}
{{- end }}
Have not tried the above approach, but am confident that this does not work (see this post). What I'd need is a default function that works for lists. I could not find any in sprig. Any Idea?
CodePudding user response:
The linked post, based on which you claim you know that the code doesn't work, does not, in the question snippet, pre-declare the variable.
In your code you do pre-declare the variable but you are making a different error. The error is that you are using :=
to assign the value to the pre-declared variable, however :=
in templates works the same as in Go itself, it initializes a new variable. You need to use =
for assignment to an existing variable.
https://pkg.go.dev/text/[email protected]#hdr-Variables
A pipeline inside an action may initialize a variable to capture the result. The initialization has syntax
$variable := pipeline
where
$variable
is the name of the variable. An action that declares a variable produces no output.Variables previously declared can also be assigned, using the syntax
$variable = pipeline
So all you need to do is to change {{- $result := $i.itemName }}
to {{- $result = $i.itemName }}
.
{{- $result := "nope" }}
{{- range $i := $items }}
{{- if and (and (hasKey $i. awesome) ($i.awesome)) !($result -eq "nope") }}
{{- $result = $i.itemName }}
{{- end }}
{{- end }}
An example to prove this is working: https://play.golang.org/p/A44yl7jo0v7