Check if array contains object with property equal to a specific value

8/15/2019

I have a helm values.yaml file that contains the following:

env:
  - name: VAR_1
    value: VALUE_1
  - name: VAR_2
    value: VALUE_2

In my helm chart I'd like to have an if that checks if .Values.env contains an item with name=VAR_1.

I tried with {{ if has "VAR_1" .Values.env }} but I am not sure how to do object comparison, or to interpolate .Values.env to .Values.env[].name (similar to jq).

-- LIvanov
go-templates
kubernetes-helm

1 Answer

8/15/2019

You need to use Looping with the range action and If/Else.

Also you can remove duplicates with uniq function, however same name with different value will be considered unique.

{{- range .Values.env | uniq -}}
  {{- if eq .name "VAR_1" -}}
    {{ .name }}: {{ .value }}
  {{- end }}
{{- end}}

Update:

Here's a hacky _helpers.tpl function that will output only the first occurrence of element with "VAR_1" name

{{- define "chart.getUniqueValue" -}}

  {{- $myDict := dict }}
  {{- $searchKey := "VAR_1" }}

  {{- range .Values.env  | reverse}}
    {{- $_ := set $myDict .name .value }}
  {{- end }}

  {{- range $k, $v := $myDict }}
    {{- if eq $searchKey $k}}
      {{- $k }} : {{ $v }}
    {{- end }}
  {{- end }}

{{- end -}}
-- edbighead
Source: StackOverflow