Helm _helpers.tpl:在其他模板定义中调用已定义的模板

Noa*_*ert 13 templates go go-templates kubernetes kubernetes-helm

Helm _helpers.tpl?

Helm允许在Kubernetes的资源文件中使用Go模板.

名为的文件_helpers.tpl通常用于使用以下语法定义Go模板助手:

{{- define "yourFnName" -}}
{{- printf "%s-%s" .Values.name .Values.version | trunc 63 -}}
{{- end -}}
Run Code Online (Sandbox Code Playgroud)

然后您可以在*.yaml资源文件中使用它,如下所示:

{{ template "yourFnName" . }}
Run Code Online (Sandbox Code Playgroud)

问题

如何在其他帮助程序定义中使用我定义的帮助程序?

例如,如果我有一个应用程序名称的帮助程序,并希望在定义中使用它来确定入口主机名?

我尝试过几种不同的方式在其他定义中调用助手.鉴于此基本辅助功能:

{{- define "host" -}}
{{- printf "%.example.com" <Somehow get result of "name" helper here> -}}
{{- end -}}
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

{{- printf "%.example.com" {{ template "name" . }} -}}
{{- printf "%.example.com" {{- template "name" . -}} -}}
{{- printf "%.example.com" ( template "name" . ) -}}
{{- printf "%.example.com" template "name" . -}}
# Separator
{{- $name := {{ template "environment" . }} -}}
{{- printf "%.example.com" $name -}}
# Separator
{{- $name := template "environment" . -}}
{{- printf "%.example.com" $name -}}
# Separator
{{- $name := environment -}}
{{- printf "%.example.com" $name -}}
Run Code Online (Sandbox Code Playgroud)

有可能做到这一点吗?如果是这样,怎么样?

Nic*_*lay 7

您应该使用嵌套模板定义.

在您的特定情况下,它是:

{{- define "host" -}}
{{ template "name" . }}.example.com
{{- end -}}
Run Code Online (Sandbox Code Playgroud)


hyp*_*low 7

您可以使用(include ... )语法。包括先前定义的模板的示例foo

{{- define "bar" -}}
{{- printf "%s-%s" (include "foo" .) .Release.Namespace | trunc 63 | trimSuffix "-" -}}
{{- end -}}
Run Code Online (Sandbox Code Playgroud)

  • 请参阅使用`template`和`include`的区别:https://github.com/technosophos/k8s-helm/blob/master/docs/charts_tips_and_tricks.md#know-your-template-functions (3认同)