在Helm图表中编写自定义函数

时间:2018-07-09 07:38:45

标签: kubernetes kubernetes-helm

我的Helm部署yaml文件中包含以下代码段:

{{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}}

我想将所有这些 if 检查放入自定义函数中,然后在此处调用该函数。使用该功能的新代码段应如下所示:

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

我将如何实现?我可能有多个部署yaml文件,每个文件都执行此条件检查,如果在每个yaml文件中进行检查,则仅调用一个函数而不是放置逻辑上繁琐的文件将很有用(只是为了减少出错的可能性)。

此外,我也不想在每个模板文件中都定义此功能,因为这样做会达到目的。

2 个答案:

答案 0 :(得分:1)

您可以在以下划线开头的文件中创建名为{em> conditional-mount 的partial template,例如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}}

然后通过以下方式在您需要的任何地方使用它:

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

这里的技巧是,您通过指向 .Values.pvc 的作用域对象 thisPvc 指定要挂载的pvc。使用Sprig dict function。 然后,您可以为其他PVC调用它,例如.Values.pvcXYZ

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

答案 1 :(得分:0)

您可能会发现{{template "foo"}} or {{block "foo"}}会做您想要的事,具体取决于数量庞大的“假设”。

helm docs在这个问题上还有很多个单词,这很不错,因为他们显然已经考虑了这个问题,而很遗憾,因为问了很多单词。