Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing custom functions in Helm charts

I have the following snippet in my Helm deployment yaml file:

{{if or .Values.ha.enabled .Values.checkpointing.enable_checkpointing .Values.enable_upgrade_hook}}
{{if eq .Values.pvc.file_prefix "file://"}}
- mountPath: {{ .Values.pvc.shared_storage_path }}/{{ template "fullname" . }}
  name: shared-pvc
{{end}}
{{end}}

I would like to put all these if checks into a custom function and just call the function here. My new snippet using the function should look like this:

{{if eq enable_mount_volume "true"}}
- mountPath: {{ .Values.pvc.shared_storage_path }}/{{ template "fullname" . }}
  name: shared-pvc
{{end}}

How would I achieve this? I may have multiple deployment yaml files, each doing this conditional check, and it would be useful to just call a function instead of putting the logic-heavy if check in each yaml file(Just to make it less error-prone).

Also, I wouldn't want to define this function in every single template file, as that would defeat the purpose.

like image 531
James Isaac Avatar asked Jul 09 '18 07:07

James Isaac


2 Answers

You can create a partial template named conditional-mount in a file starting with underscore, for example, templates/_conditional-mount.tpl:

{{define "conditional-mount"}}
{{if or .Values.ha.enabled .Values.checkpointing.enable_checkpointing .Values.enable_upgrade_hook}}
{{if eq .thisPvc.file_prefix "file://"}}
- mountPath: {{ .thisPvc.shared_storage_path }}/{{ template "fullname" . }}
  name: shared-pvc
{{end}}
{{end}}
{{end}}

And then use it you anywhere you need via:

{{include "conditional-mount" (dict "Values" .Values "thisPvc" .Values.pvc)}}

The trick here is that you specify a pvc to be mounted via the scope object thisPvc pointing to the .Values.pvc. The Sprig dict function is used. You can then call it for different PVC, for example, .Values.pvcXYZ:

{{include "conditional-mount" (dict "Values" .Values "thisPvc" .Values.pvcXYZ)}}
like image 139
Maxwell Avatar answered Oct 25 '22 12:10

Maxwell


You may find {{template "foo"}} or {{block "foo"}} will do what you want, depending on a huge number "what ifs".

The helm docs have a lot more words around that very problem, which is great because they have obviously considered it, and sad because whew what a lot of words.

like image 24
mdaniel Avatar answered Oct 25 '22 12:10

mdaniel