Difference between revisions of "Helm Templates"

From NovaOrdis Knowledge Base
Jump to: navigation, search
Line 386: Line 386:
  ... {{ template myChart.postgresqlServiceName . }} ...
  ... {{ template myChart.postgresqlServiceName . }} ...
For more details on rendering, see [[#template|template]] below.
====Named Templates and Whitespace Handling====
====Named Templates and Whitespace Handling====

Revision as of 22:04, 19 September 2019




Templates are files living under a chart's templates/ directory. They are written in YAML with Helm templates extensions. Upon processing by Helm, they become Kubernetes manifest files. Helm template extensions are written in the Help template language, which is based on Go templates.

The templates/ Directory

The 'templates' directory contains templates that, after combination with values, will the Kubernetes manifests. When Tiller evaluates a chart, it will send all of the files in the directory - with a few exceptions - through the template rendering engine, then collect the results and send them to to Kubernetes. Note that the NOTES.txt and _helpers.tpl files are also subject to template rendering, but they are not sent to Kubernetes as manifests.

Template names do not follow a rigid naming pattern. It is, however, recommended to use the suffix .yaml for YAML files and .tpl for helpers.

The files whose name begins with an underscore ('_') are assumed to not have a manifest inside, so they are not rendered into manifest definitions. However, they are available everywhere within other chart templates for use. These files are conventionally used to store partials and helpers. _helpers.tpl is the default location for template partials.

Installation and De-Installation Order

During installation, Helm collects all of the resources in a given chart and its dependences, groups them by resource type, and installs them in the order specified here https://github.com/helm/helm/blob/release-2.14/pkg/tiller/kind_sorter.go#L29-L57. Upon de-installation the order is reversed: https://github.com/helm/helm/blob/release-2.14/pkg/tiller/kind_sorter.go#L62-L90

Template Comments

 # This is a comment
{{/* Generate basic labels */}}

Multi-Line Comments

 {{- /*
 This is another 
 */ -}}

Template Directives

A template directive, sometimes also referred as tag, is enclosed in {{ and }} blocks, and it is recommended to pad the directive with space at its left and right. The simplest directive renders a value. A value is a namespaced object, where each dot (.) separates each namespaced element. A leading dot indicates that we start with the top-most namespace for the scope.

kind: ConfigMap
  name: {{ .Release.Name }}-configmap

Directives may also include functions and other constructs.

With the exception of the multi-line comments, all directives must be specified on one line only. Space present inside a directive is irrelevant, the following formats are equivalent:

{{ .Values.color }}
{{            .Values.color               }}

The recommended format is to allow for a space after '{{' and before '}}':

{{ .Values.color }}

Directives and Whitespace Handling

The spaces inside a directive is irrelevant (we cannot have newlines inside a directive, all directives must be specified on a single line). The '{{' and '}}' directive delimiters, without any other modifications, leave the template whitespace surrounding them alone, and do not interfere with it in any way. A hyphen '-' placed after the '{{' delimiter or before the '}}' delimiter instructs the rendering engine to trim the whitespace preceding, respectively trailing the delimiter. Whitespace includes spaces, tabs, newline ('\n') and carriage return ('\r'). When encountering "-", the template engine will simply drop the corresponding whitespace until a non-whitespace character is found.

  color: {{ .Values.color }}

will produce (assuming that "color" is declared to be "blue" in values.yaml:

  color: blue

To trim preceding whitespace, use '{{-'.

  color: {{- .Values.color }}

will produce:


To trim trailing whitespace (whitespace includes newlines), use '-}}'.

  color: {{ .Values.color -}}

will produce:

  color: bluespec:

(which is something you most like don't want).

For details related to whitespace handling when declaring named templates, see Named Templates and Whitespace Handling, below.


Scopes are declared with 'with'.


Template Objects

Objects are passed into a template from the template engine. The template directives can create new objects and pass them around. There are also built-in objects, which are made available by default. Objects can be simple - have just one value -, or they can contain other objects or functions. For example the "Release" built-in object contains several other objects (like "Release.Name"). The "Files" object contains functions.

Built-in Objects

Built-in Objects
The built-in values always begin with a capital letter, based on Go's naming convention. For a fully working examples of built-in objects replacement see:


This object contains value passed into the template from the Chart.yaml file. An existing field is available as (note leading dot) .Chart.<UpperCasedFirstLetterFieldName>. It is important to capitalize the first letter of the field name, otherwise the directive evaluation fails.


{{ .Chart.Name }}
{{ .Chart.Version }}


This object contains values passed into template from the values.yaml file and from other user sources. An existing field is available as (note leading dot) .Values.<fieldName>. Unlike in Chart's case, the fields are allowed to keep their original capitalization. For example, a value declared as such in values.yaml:

size: 10

can be references in a template as:

kind: ConfigMap
  size: {{ .Values.size }}

Values can contain structured content:

  size: 10
  shape: "large"

can be referenced in template as:

kind: ConfigMap
  size: {{ .Values.characteristics.size }}
  shape: {{ .Values.characteristics.shape }}

While structuring data this way is possible, the recommendation is to keep values trees shallow, favoring flatness.

In case the structure contains an array, individual elements can be referred from the template as such:


This object describes the release itself.


Exposes the release name:

{{ .Release.Name }}


Exposes the release revision:

{{ .Release.Revision }}


Exposes the time of the release:

{{ .Release.Time }}


Exposes the namespace to be released info, if the manifest does not override:

{{ .Release.Namespace }}


This is set to true if the current operation is an upgrade or rollback.

{{ .Release.IsUpgrade }}


This is set to true if the current operation is an install.

{{ .Release.IsInstall }}


Exposes the releasing service - always Tiller


The object provide access to all non-special files in the chart. It cannot be used to access templates. The access is provided via several functions:


{{ .Files.Get <file-name> }}


Accessing Files inside Templates

Accessing Files inside Templates



Provides information about the capabilities of the Kubernetes cluster:

{{ .Capabilities.APIVersions }}
{{ .Capabilities.APIVersions.Has }}
{{ .Capabilities.KubeVersion }}
{{ .Capabilities.KubeVersion.Major|
{{ .Capabilities.TillerVersion }}


Contains information about the current template that is being executed:

{{ .Template.Name }}
{{ .Template.BasePath }}

Template Functions

Template Functions and Pipelines
Go Templates
sprig Template Functions

A template function modifies data provided to the template via template objects, and it is declared inside the template, in a template directive. Template functions follow the syntax:

functionName arg1 arg2 ...


{{ quote .Values.color }}

Helm Template Function Reference


Operators are Functions

Operators are implemented as functions that return a boolean value:

 {{ eq Values.color "blue" }}
 {{ ne }}
 {{ lt }}
 {{ gt }}
 {{ and }}
 {{ or }}
 {{ not }}

Accessing Array Elements

To access a specific element of an array data structure, use the index function. The index function is 0-based.

Assuming we declare a simple array:

  - 'blue'
  - 'red'
  - 'green'

then the first element of the array can be accessed with:

{{ index .Values.colors 0 }}

The directive is rendered to "blue".

When the array contains maps:

  - name: blue
    shade: dark
  - name: red
    shade: light

the fields of the maps can be accessed with - note (...):

{{ (index .Values.colors 0).name }}

This pattern can be extrapolated to more complex data structures.

Template Pipelines

{{ <object> | <function1> | <function2>  }}
{{ .Values.color | upper | repeat 5 }}

Template Control Structures

Flow control structures are called "actions".



if/else can be used to create conditional blocks.



Modifying scope using with

with specifies a scope.



Looping with the range Action

range provides a "for each" loop.


Named Template Actions

Named Templates

A named template, sometimes called a partial, a subtemplate or an embedded template, is a template define inside of a file, and given a names. There are two different ways to create named templates, with the define action and with the template action.

Template names are global. That means if two template are declared with the same name, whichever is loaded last will be the one that will be used. Moreover, the templates in subcharts, which we are not necessarily too familiar with, are compiled together with top-level templates, so it is possible to run into template name collisions we are not aware of. For this reason, it is a good practice to name your templates with unique, chart-specific names.

One popular naming convention is to prefix the name of each defined template with the name of the chart:

{{ define "mychart.labels" }}

If everyone follows the same convention, chart-specific named templates get their own namespace and that decreases the probability of conflict that may arise due to two different charts that implement templates with the same name.


Declaring and Using Templates with define

define declares a new named template inside of a template file, conventionally _helpers.tpl:

{{/* Generate basic labels */}}
{{- define "mychart.labels" }}
    generator: helm
    date: {{ now | htmlDate }}
{{- end }}

By convention, define functions should have a simple documentation block {{/* ... */}} describing what they do.

The body of the partial may include directives.

Partials may be used instead of variables, by declaring a template that acts like a variable:

Compute the service name that depends on the release name. This partial should be inlined every time the service name is needed.
{{- define "myChart.postgresqlServiceName" -}}
{{- printf "%s-postgresql" .Release.Name -}}
{{- end -}}

When we need the service name in a template, we render it as such:

 ... {{ template myChart.postgresqlServiceName . }} ...

For more details on rendering, see template below.

Named Templates and Whitespace Handling

Unless controlled with '{{-' and '-}}', the whitespace specified inside the partial are preserved and projected in the rendered result.

Named Template Recipes

Named Template Recipes


A partial defined as such can be embedded inside other template with the template action:

kind: ConfigMap
 name: ...
 {{- template "mychart.labels" }}

When the template engine reads the file that contains the partial, it will store away the reference to "mychart.labels" until template "mychart.labels" is called. Then it will render that template inline. After rendering, the result will look like this:

kind: ConfigMap
 name: ...
   generator: helm
   date: 2019-08-29

Setting the Scope of a Template. The "template" action allows passing a scope. By default, no scope is passed by default, so objects like .Chart.Name are not found and rendered to blank space.

To pass the scope of the calling template, use "template" as such (note the dot):

 {{- template "mychart.labels" . }}

In the above example, we passed the top-level (".") scope. We can pass whatever scope (template object) we want:

 {{- template "mychart.labels" .Values }}


 {{- template "mychart.labels" .Values.favorite }}


Avoid using Blocks

block declares a special kind of fillable template area.


The include Function

The include Function


Template Variables



Configmap and Secrets Utility Functions

Configmap and Secrets Utility Functions


Debugging Templates

Debugging Templates