Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helm _helpers.tpl: Calling defined templates in other template definitions

Helm _helpers.tpl?

Helm allows for the use of Go templating in resource files for Kubernetes.

A file named _helpers.tpl is usually used to define Go template helpers with this syntax:

{{- define "yourFnName" -}}
{{- printf "%s-%s" .Values.name .Values.version | trunc 63 -}}
{{- end -}}

Which you can then use in your *.yaml resource files like so:

{{ template "yourFnName" . }}

The Question

How can I use the helpers I define, in other helper definitions?

For example, what if I have a helper for the application name, and want to use that in the definition for a helper which determines the ingress host name?

I have tried calling helpers in other definitions a couple different ways. Given this basic helper function:

{{- define "host" -}}
{{- printf "%.example.com" <Somehow get result of "name" helper here> -}}
{{- end -}}

I have tried the following:

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

Is it possible to even do this? If so, how?

like image 561
Noah Huppert Avatar asked Oct 12 '17 21:10

Noah Huppert


People also ask

What is _helpers TPL file in Helm?

tpl? Helm allows for the use of Go templating in resource files for Kubernetes. A file named _helpers.tpl is usually used to define Go template helpers with this syntax: {{- define "yourFnName" -}} {{- printf "%s-%s" .Values.name .Values.version | trunc 63 -}} {{- end -}}

Does Helm use Go templates?

While we talk about the "Helm template language" as if it is Helm-specific, it is actually a combination of the Go template language, some extra functions, and a variety of wrappers to expose certain objects to the templates.

What does {{- mean in Helm?

{{- (with the dash and space added) indicates that whitespace should be chomped left, while -}} means whitespace to the right should be consumed.


2 Answers

You can use (include ... ) syntax. Example of including previously defined template foo:

{{- define "bar" -}}
{{- printf "%s-%s" (include "foo" .) .Release.Namespace | trunc 63 | trimSuffix "-" -}}
{{- end -}}
like image 113
hypnoglow Avatar answered Oct 09 '22 01:10

hypnoglow


You should use Nested template definitions.

In your particular case it is:

{{- define "host" -}}
{{ template "name" . }}.example.com
{{- end -}}
like image 17
nickgryg Avatar answered Oct 09 '22 01:10

nickgryg