代码之家  ›  专栏  ›  技术社区  ›  rockyroad

在舵图中编写自定义函数

  •  3
  • rockyroad  · 技术社区  · 7 年前

    在我的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 eq enable_mount_volume "true"}}
    - mountPath: {{ .Values.pvc.shared_storage_path }}/{{ template "fullname" . }}
      name: shared-pvc
    {{end}}
    

    我要如何做到这一点?我可能有多个部署yaml文件,每个文件都执行这个条件检查,如果签入每个yaml文件,只调用一个函数而不是让逻辑变得繁重(只是为了减少出错的可能性)。

    另外,我不想在每个模板文件中都定义这个函数,因为这样做会破坏目标。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Maxwell    7 年前

    您可以创建 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)}}
    

    这里的诀窍是指定要通过scope对象安装的pvc 这种聚氯乙烯 指向 .值.pvc Sprig dict function 被使用。 你可以用不同的PVC来称呼它,例如, .Values.pvcXYZ

    {{include "conditional-mount" (dict "Values" .Values "thisPvc" .Values.pvcXYZ)}}
    
        2
  •  1
  •   mdaniel    7 年前

    你会发现 {{template "foo"}} or {{block "foo"}}

    这个 helm docs 有一个 许多