CoursesHelmIntermediate

Functions, pipelines & named templates

DRY templates with helpers.

Intermediate12 min · lesson 6 of 12

Sprig gives Helm templates a large standard library — string functions (upper, trimSuffix, printf), defaults (default, required), encoding (b64enc, toYaml, toJson), lists and dicts, and flow helpers. You chain them with pipelines: {{ .Values.name | default "app" | quote }} passes the value left-to-right through each function. Two you will use constantly are default (supply a fallback) and required (fail the render with a clear message if a value is missing).

template
name: {{ .Values.name | default .Chart.Name | quote }}
replicas: {{ .Values.replicaCount | default 1 }}
# fail early with a helpful message if a mandatory value is absent:
image: {{ required "image.repository is required!" .Values.image.repository }}
config: |
{{- toYaml .Values.config | nindent 2 }} # render a map as indented YAML

Named templates and _helpers.tpl

Repeated blocks — a standard label set, a name convention — go into named templates (define/template, or include) kept in templates/_helpers.tpl. include renders a named template and, unlike template, can be piped (so you can indent its output). Charts scaffolded by helm create ship helpers like <chart>.labels and <chart>.fullname exactly for this. Named templates are how you keep a chart DRY as it grows.

templates/_helpers.tpl
{{- define "payments.labels" -}}
app.kubernetes.io/name: {{ .Chart.Name }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}
# use it, correctly indented:
# metadata:
# labels:
# {{- include "payments.labels" . | nindent 6 }}
Use include (not template) when you need to pipe
The built-in template action cannot be piped, so you cannot indent its output — which breaks YAML the moment a helper is nested. include does the same rendering but returns a string you can pipe into nindent/indent. Standardize on include with nindent for helpers, and reserve toYaml | nindent for rendering values maps; getting indentation right here prevents most “invalid YAML” chart failures.