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

Jam*_*aac 5 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}}
Run Code Online (Sandbox Code Playgroud)

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

{{if eq enable_mount_volume "true"}}
- mountPath: {{ .Values.pvc.shared_storage_path }}/{{ template "fullname" . }}
  name: shared-pvc
{{end}}
Run Code Online (Sandbox Code Playgroud)

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

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

Max*_*ell 7

您可以在以下划线开头的文件中创建名为条件挂载的部分模板,例如: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}}
Run Code Online (Sandbox Code Playgroud)

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

{{include "conditional-mount" (dict "Values" .Values "thisPvc" .Values.pvc)}}
Run Code Online (Sandbox Code Playgroud)

这里的技巧是,您通过指向.Values.pvc 的作用域对象thisPvc指定要安装的 pvc 。使用Sprig dict 函数。然后您可以为不同的 PVC 调用它,例如:.Values.pvcXYZ

{{include "conditional-mount" (dict "Values" .Values "thisPvc" .Values.pvcXYZ)}}
Run Code Online (Sandbox Code Playgroud)


mda*_*iel 2

你可能会发现{{template "foo"}}{{block "foo"}}会做你想做的事,这取决于大量的“假设”。

helm文档围绕这个问题有更多的文字,这很好,因为他们显然已经考虑过这个问题,但令人难过的是,哇,太多文字了。