Writing custom functions in Helm charts

7/9/2018

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.

-- James Isaac
kubernetes
kubernetes-helm

2 Answers

7/10/2018

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.

-- mdaniel
Source: StackOverflow

10/4/2018

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)}}
-- Maxwell
Source: StackOverflow