working with helm chart - checking for nil and print out variables
We can print out helm variables by either using the following commands
To print single value
{{ printf "Value of myVar: %v" .Values.myVar }}
{{ toYaml .Values | indent 2 }}
Let's say we are trying to create a template for object that might be nil or might
contains value so we need to check for parent object and then do further checks.
This can be troublesome.
To check for object nil, we can use "dig" or "get"
Use dig
{{- $vals := .Values | toJson | fromJson -}} <- This is to prevent nil
{{- $workloadIdentityEnabled := dig "security" "workloadIdentity" "enabled" false $vals -}}
{{- $clientId := dig "security" "workloadIdentity" "clientId" "" $vals -}}
Or you want to use "get" here
{{- $security := get .Values "security" | default dict -}}
{{- $workloadIdentity := get $security "workloadIdentity" | default dict -}}
{{- $workloadIdentityEnabled := $workloadIdentity.enabled | default false -}}
{{- $clientId := $workloadIdentity.clientId | default "" -}}
To helper
You can convert it to helper by placingt his in
_helper.tpl
{{ $wi := include "test-chart.workloadIdentity" . | fromJson }}
{{ $wi.enabled }} → bool
{{ $wi.clientId }} → string (may be empty)
Output is always a JSON object: {"enabled": false, "clientId": ""}
*/}}
{{- define "test-chart.workloadIdentity" -}}
{{- $vals := .Values | toJson | fromJson -}}
{{- $enabled := dig "security" "workloadIdentity" "enabled" false $vals -}}
{{- $clientId := dig "security" "workloadIdentity" "clientId" "" $vals -}}
{{- dict "enabled" $enabled "clientId" $clientId | toJson -}}
{{- end -}}
And then reference that in the deployment or other template
{{- $wi := include "test-chart.workloadIdentity" . | fromJson -}}
{{- $workloadIdentityEnabled := $wi.enabled -}}
{{- $clientId := $wi.clientId -}}
And then somewhere in your code :-
labels:
{{- if and $workloadIdentityEnabled $clientId }}
workloadIdentityClientId: {{ $clientId | quote }}
{{- end }}
Comments