Skip to content
Hands-on IT IT Drills

Day 6: Building Blocks – define, include, _helpers.tpl {#tag06}

Goal: Define names and labels once in _helpers.tpl and use them everywhere with include – and know the typical mistakes that make building blocks dangerous. · Duration: approx. 45 min · Prerequisite: Day 5

Briefing

  • define creates a named template, include calls it and returns a string that you process further with nindent.
  • The dot at the end of include "notes.labels" . passes the context. Without it the building block has nothing to work with.
  • Named templates are global across the chart and its subcharts. So always use a chart prefix: notes.fullname, never fullname.
  • Selector labels must never change after installation. That is why there are two building blocks: notes.selectorLabels (stable) and notes.labels (everything).
 _helpers.tpl                          deployment.yaml, service.yaml, ...
 ├─ notes.name            (base for the three below)
 ├─ notes.fullname        ──include──>  metadata.name
 ├─ notes.selectorLabels  ──include──>  spec.selector / Service selector
 └─ notes.labels          ──include──>  metadata.labels and Pod labels

Drill 1: Create _helpers.tpl

# on prod
mkdir -p ~/helm/tag06 && cd ~/helm/charts
cat > notes/templates/_helpers.tpl <<'EOF'
{{/* notes/templates/_helpers.tpl – Stand Tag 06 */}}

{{/* Name des Charts, über nameOverride änderbar */}}
{{- define "notes.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end }}

{{/* Vollständiger Name: Release, ggf. mit Chart-Namen, max. 63 Zeichen */}}
{{- define "notes.fullname" -}}
{{- if .Values.fullnameOverride }}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }}
{{- else if contains (include "notes.name" .) .Release.Name }}
{{- .Release.Name | trunc 63 | trimSuffix "-" }}
{{- else }}
{{- printf "%s-%s" .Release.Name (include "notes.name" .) | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- end }}

{{/* Selektor-Labels: dürfen sich nach der Installation nie ändern */}}
{{- define "notes.selectorLabels" -}}
app.kubernetes.io/name: {{ include "notes.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end }}

{{/* Alle Labels: Selektor-Labels plus Version, Chart, Verwalter */}}
{{- define "notes.labels" -}}
{{ include "notes.selectorLabels" . }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" }}
{{- with .Values.team }}
team: {{ . | quote }}
{{- end }}
{{- end }}
EOF
cat >> notes/values.yaml <<'EOF'

# -- Ersetzt den Chart-Namen in Namen und Labels
nameOverride: ""
# -- Ersetzt den vollständigen Namen aller Objekte
fullnameOverride: ""
EOF
sed -i 's/Stand Tag 05/Stand Tag 06/' notes/values.yaml
sed -i 's/^version: .*/version: 0.5.0/; s/Tag 05/Tag 06/' notes/Chart.yaml
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "notes.fullname" . }}-test
  labels:
    {{- include "notes.labels" . | nindent 4 }}
data: {}
EOF
for r in notes notes-dev demo; do
  helm template $r ./notes -s templates/spielwiese.yaml | grep -m1 'name:'; done
helm template notes ./notes -s templates/spielwiese.yaml --set team=plattform \
  | sed -n '/labels/,$p'

The German comments in _helpers.tpl describe each block: the chart name (changeable via nameOverride), the full name (release, possibly with chart name, max. 63 characters), the selector labels (‘must never change after installation’) and all labels (selector labels plus version, chart, manager). The new values replace the chart name in names and labels (nameOverride) or the full name of all objects (fullnameOverride).

Expected:

  name: notes-test
  name: notes-dev-test
  name: demo-notes-test
  labels:
    app.kubernetes.io/name: notes
    app.kubernetes.io/instance: notes
    app.kubernetes.io/version: "0.7.1"
    app.kubernetes.io/managed-by: Helm
    helm.sh/chart: notes-0.5.0
    team: "plattform"
data: {}

If the release name already contains the chart name, notes.fullname takes only the release name – otherwise everything would be called notes-notes. {{- define … -}} with a minus on both sides is right here: a building block should deliver no blank lines before or after it. replace "+" "_" turns a version like 1.0.0+build.7 into a valid label.

Save your progress? Sign up for free

Drill 2: Why trunc 63?

Many Kubernetes names are DNS labels and may have at most 63 characters.

# on prod
helm template $(printf 'r%.0s' {1..54}) ./notes 2>&1 | head -1
L=$(printf 'x%.0s' {1..70})
helm template notes ./notes -s templates/spielwiese.yaml --set fullnameOverride=$L \
  | yq '.metadata.name | length'

Expected:

level=ERROR msg="release name check failed" error="release name \"rrrrrrrrrrrrrrrrr…\":
invalid release name, must match regex ^[a-z0-9]([-a-z0-9]*[a-z0-9])?…$ and the length
must not be longer than 53"
68

Helm itself limits release names to 53 characters. trunc 63 protects against long chart names and fullnameOverride. But watch out: the -test comes after truncation – 68 characters. For a ConfigMap that does not matter (up to 253 allowed), for a Service it does. The Challenge builds a building block that gets this right.

Save your progress? Sign up for free

Drill 3: Switch all templates over

# on prod
rm notes/templates/spielwiese.yaml
cat > notes/templates/deployment.yaml <<'EOF'
{{/* notes/templates/deployment.yaml – Stand Tag 06 */}}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "notes.fullname" . }}
  labels:
    {{- include "notes.labels" . | nindent 4 }}
spec:
  replicas: {{ hasKey .Values "replicaCount" | ternary .Values.replicaCount 2 }}
  selector:
    matchLabels:
      {{- include "notes.selectorLabels" . | nindent 6 }}
  template:
    metadata:
      labels:
        {{- include "notes.labels" . | nindent 8 }}
    spec:
      containers:
        - name: notes-api
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          ports: [{name: http, containerPort: 8080}]
          env:
            - name: NOTES_API_KEY
              value: {{ .Values.apiKey | quote }}
            {{- range $name, $value := .Values.env }}
            - name: {{ $name }}
              value: {{ $value | quote }}
            {{- end }}
          readinessProbe:
            httpGet: {path: /healthz, port: http}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
EOF
cat > notes/templates/service.yaml <<'EOF'
{{/* notes/templates/service.yaml – Stand Tag 06 */}}
apiVersion: v1
kind: Service
metadata:
  name: {{ include "notes.fullname" . }}
  labels:
    {{- include "notes.labels" . | nindent 4 }}
spec:
  selector:
    {{- include "notes.selectorLabels" . | nindent 4 }}
  ports:
    - name: http
      port: {{ .Values.service.port }}
      targetPort: http
EOF
cat > notes/templates/NOTES.txt <<'EOF'
{{- /* notes/templates/NOTES.txt – Stand Tag 06 */ -}}
notes {{ .Chart.AppVersion }} ist als Release {{ .Release.Name }} installiert.
Test: kubectl -n {{ .Release.Namespace }} port-forward \
  svc/{{ include "notes.fullname" . }} 8080:{{ .Values.service.port }}
EOF

The ConfigMap and the Ingress get the name and labels as well. In the Ingress the Service name sits inside a range loop – there the context is $:

# on prod
cat > notes/templates/configmap.yaml <<'EOF'
{{/* notes/templates/configmap.yaml – Stand Tag 06 */}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "notes.fullname" . }}-info
  labels:
    {{- include "notes.labels" . | nindent 4 }}
data:
  release: {{ .Release.Name }}
  namespace: {{ .Release.Namespace }}
  revision: {{ .Release.Revision | quote }}
  installOderUpgrade: {{ ternary "upgrade" "install" .Release.IsUpgrade }}
  chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
  app: {{ .Chart.AppVersion | quote }}
  template: {{ .Template.Name }}
  basePath: {{ .Template.BasePath }}
  kube: {{ .Capabilities.KubeVersion.Version }}
  helm: {{ .Capabilities.HelmVersion.Version }}
  gatewayAPI: {{ .Capabilities.APIVersions.Has "gateway.networking.k8s.io/v1" | quote }}
  httpRoute: {{ .Capabilities.APIVersions.Has "gateway.networking.k8s.io/v1/HTTPRoute"
    | quote }}
EOF
cat > notes/templates/ingress.yaml <<'EOF'
{{/* notes/templates/ingress.yaml – Stand Tag 06 */}}
{{- if and .Values.ingress.enabled .Values.ingress.hosts }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: {{ include "notes.fullname" . }}
  labels:
    {{- include "notes.labels" . | nindent 4 }}
  {{- if eq .Values.ingress.className "traefik" }}
  annotations:
    traefik.ingress.kubernetes.io/router.entrypoints: web
  {{- end }}
spec:
  {{- with .Values.ingress.className }}
  ingressClassName: {{ . }}
  {{- end }}
  rules:
    {{- range .Values.ingress.hosts }}
    - host: {{ . | quote }}
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: {{ include "notes.fullname" $ }}
                port:
                  number: {{ $.Values.service.port }}
    {{- end }}
{{- end }}
EOF
helm lint notes | tail -1
helm template notes ./notes -f values/prod.yaml | grep -E '^kind|^  name:'

Expected:

1 chart(s) linted, 0 chart(s) failed
kind: ConfigMap
  name: notes-info
kind: Service
  name: notes
kind: Deployment
  name: notes
kind: Ingress
  name: notes

Now the upgrade. notes-api becomes notes:

# on prod
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | sed -n '/NOTES/,$p'
kubectl -n notes get deploy,svc,ingress
curl -s -H 'Host: notes.lab' localhost/healthz

Expected:

NOTES:
notes 0.7.1 ist als Release notes installiert.
Test: kubectl -n notes port-forward \
  svc/notes 8080:80
NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/notes   2/2     2            2           4s

NAME            TYPE        CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGE
service/notes   ClusterIP   10.43.86.52   <none>        80/TCP    4s

NAME                              CLASS     HOSTS                     ADDRESS  ...
ingress.networking.k8s.io/notes   traefik   notes.lab,api.notes.lab   172.16.0.123 ...
ok

The NOTES line says ‘notes 0.7.1 is installed as release notes’. A new name is a new object for Kubernetes: Helm creates notes and deletes notes-api because it is missing from the new manifest. In production that means a short gap – so settle on names early.

Save your progress? Sign up for free

Drill 4: Forgetting the dot

# on prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "notes.fullname" }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml
sed -i 's/fullname" }}/fullname" .Values }}/' notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml

Expected:

Error: notes/templates/spielwiese.yaml:4:11
  executing "notes/templates/spielwiese.yaml" at <include>:
    wrong number of args for include: want 2 got 1
Error: notes/templates/spielwiese.yaml:4:11
  executing "notes/templates/spielwiese.yaml" at <include "notes.fullname" .Values>:
    error calling include:
notes/templates/_helpers.tpl:10:14
  executing "notes.fullname" at <.Values.fullnameOverride>:
    nil pointer evaluating interface {}.fullnameOverride

Without a context, include refuses straight away. With the wrong context the building block runs and looks for .Values.fullnameOverride inside .Values – that is, .Values.Values.fullnameOverride. The message shows file, line and column in the helper.

Save your progress? Sign up for free

Drill 5: template or include?

# on prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: spiel
  labels:
    {{- template "notes.labels" . | nindent 4 }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml
sed -i 's/{{- template.*/{{ template "notes.selectorLabels" . }}/' \
  notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml | sed -n '3,$p'
rm notes/templates/spielwiese.yaml

Expected:

Error: notes/templates/spielwiese.yaml:6:44
  executing "notes/templates/spielwiese.yaml" at <4>:
    wrong type for value; expected string; got common.Values
apiVersion: v1
kind: ConfigMap
metadata:
  name: spiel
  labels:
    app.kubernetes.io/name: notes
app.kubernetes.io/instance: notes

template is an action, not a function: it writes straight to the output and cannot be used in a pipe. Without nindent only the first line is indented – the second lands at the margin and becomes a top-level field. So in practice you always use include.

Save your progress? Sign up for free

Drill 6: Collision of global names

Two charts, both define fullname without a prefix – a parent chart (eltern, German for ‘parents’) and a subchart kind (‘child’) in charts/ (more on that on Day 9):

# on prod
cd ~/helm/tag06
mkdir -p eltern/templates eltern/charts/kind/templates
printf 'apiVersion: v2\nname: eltern\nversion: 0.1.0\n' > eltern/Chart.yaml
printf 'apiVersion: v2\nname: kind\nversion: 0.1.0\n' > eltern/charts/kind/Chart.yaml
echo '{{- define "fullname" -}}eltern-{{ .Release.Name }}{{- end }}' \
  > eltern/templates/_helpers.tpl
echo '{{- define "fullname" -}}kind-{{ .Release.Name }}{{- end }}' \
  > eltern/charts/kind/templates/_helpers.tpl
cat > eltern/templates/cm.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "fullname" . }}
EOF
cp eltern/templates/cm.yaml eltern/charts/kind/templates/cm.yaml
helm template x ./eltern | grep -E 'Source|name:'
helm install x ./eltern -n tag06 --create-namespace | grep STATUS
kubectl -n tag06 get configmap

Expected:

# Source: eltern/charts/kind/templates/cm.yaml
  name: eltern-x
# Source: eltern/templates/cm.yaml
  name: eltern-x
STATUS: deployed
NAME               DATA   AGE
eltern-x           0      1s
kube-root-ca.crt   1      11s

The parent chart’s definition overrides the subchart’s. Both ConfigMaps get the same name, and Helm 4 installs without an error – in the end there is only one ConfigMap from the chart. Kubernetes creates kube-root-ca.crt in every namespace itself. Its age depends on when tag06 was created – --create-namespace only creates it if it is missing. With a prefix the spook is gone:

# on prod
helm uninstall x -n tag06
sed -i 's/"fullname"/"eltern.fullname"/' eltern/templates/*
sed -i 's/"fullname"/"kind.fullname"/' eltern/charts/kind/templates/*
helm template x ./eltern | grep 'name:'

Expected:

release "x" uninstalled
  name: kind-x
  name: eltern-x

Save your progress? Sign up for free

Drill 7: Version in the selector

What happens if someone puts the version into the selector labels? You try it on a copy:

# on prod
cp -r ~/helm/charts/notes .
V='app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}'
sed -i "/^app.kubernetes.io\/instance: {{ .Release.Name }}$/a $V" \
  notes/templates/_helpers.tpl
helm install sel ./notes -n tag06 --set replicaCount=1 --wait | grep STATUS
sed -i 's/^appVersion: "0.7.1"/appVersion: "0.7.2"/' notes/Chart.yaml
helm upgrade sel ./notes -n tag06 --set replicaCount=1 --wait
helm history sel -n tag06 --max 1 -o json | jq -r '.[0].status'

Expected:

STATUS: deployed
Error: UPGRADE FAILED: server-side apply failed for object tag06/sel-notes apps/v1,
Kind=Deployment: Deployment.apps "sel-notes" is invalid: spec.selector: Invalid value:
{"matchLabels":{"app.kubernetes.io/instance":"sel","app.kubernetes.io/name":"notes",
"app.kubernetes.io/version":"0.7.2"}}: field is immutable
failed

A Deployment’s spec.selector is immutable. With the version in it, the first upgrade to a new app version fails. Day 19 shows how to get a release out of this state.

Save your progress? Sign up for free

Exercise: Speed Drills

  1. What is the Service called if the release is named shop? Target time: 20 s
  2. Show the selector of the running Deployment notes. Target time: 20 s
  3. Show all objects of the release notes via the instance label. Target time: 30 s
  4. List all named templates in _helpers.tpl. Target time: 15 s

Solution

# on prod
cd ~/helm/charts
helm template shop ./notes -s templates/service.yaml | yq .metadata.name
kubectl -n notes get deploy notes -o jsonpath='{.spec.selector.matchLabels}{"\n"}'
kubectl -n notes get deploy,svc,ingress,cm -l app.kubernetes.io/instance=notes -o name
grep -o 'define "[a-zA-Z.]*"' notes/templates/_helpers.tpl

Expected:

shop-notes
{"app.kubernetes.io/instance":"notes","app.kubernetes.io/name":"notes"}
deployment.apps/notes
service/notes
ingress.networking.k8s.io/notes
configmap/notes-info
define "notes.name"
define "notes.fullname"
define "notes.selectorLabels"
define "notes.labels"

Save your progress? Sign up for free

Checkpoint

# on prod
helm list -n notes

Expected: Revision 14, notes-0.5.0, deployed.

# on prod
kubectl -n notes get deploy notes -o jsonpath='{.metadata.labels.helm\.sh/chart}{"\n"}'

Expected: notes-0.5.0

# on prod
curl -s -H 'Host: api.notes.lab' localhost/version; echo

Expected: 0.7.1

Challenge

In a copy, build a building block notes.componentName that returns a full name with a suffix and is guaranteed to be at most 63 characters long – without cutting off the suffix. Use it for the ConfigMap (-info) and test with a 70-character fullnameOverride.

Hint: A building block gets only one argument. You pack several into a map with dict.

Solution

# on prod
cd ~/helm/tag06 && rm -rf notes && cp -r ~/helm/charts/notes .
cat >> notes/templates/_helpers.tpl <<'EOF'

{{/* Name mit Suffix: Basis kürzen, damit -suffix in 63 Zeichen passt */}}
{{- define "notes.componentName" -}}
{{- $basis := include "notes.fullname" .ctx | trunc (int (sub 62 (len .suffix))) }}
{{- printf "%s-%s" ($basis | trimSuffix "-") .suffix }}
{{- end }}
EOF
N='{{ include "notes.componentName" (dict "ctx" . "suffix" "info") }}'
sed -i "/-info$/c\\  name: $N" notes/templates/configmap.yaml
L=$(printf 'x%.0s' {1..70})
helm template notes ./notes -s templates/configmap.yaml | yq .metadata.name
helm template notes ./notes -s templates/configmap.yaml --set fullnameOverride=$L \
  | yq '.metadata.name, (.metadata.name | length)'

Expected:

notes-info
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-info
63

dict "ctx" . "suffix" "info" builds a map; inside the building block the dot is this map, hence .ctx and .suffix. The base ($basis) is truncated to 62 - len(suffix), then the hyphen and the suffix are added. A naive printf … | trunc 63 would have cut off the -info – and the ConfigMaps -info, -config and -files of the coming days would all end up with the same name.

Save your progress? Sign up for free

Cleanup

# on prod
helm uninstall sel -n tag06
kubectl delete namespace tag06
cd ~/helm/charts
git add -A
git commit -qm "Tag 06: _helpers.tpl, Namen und Labels, notes 0.5.0"

Expected:

release "sel" uninstalled
namespace "tag06" deleted

Interview Note

  • Why include instead of template? include returns a string that you indent with nindent. template writes straight to the output and cannot be used in a pipe.
  • Why a chart prefix for named templates? They are global across all charts of a release. Identical names silently override each other – including identically named objects.
  • What belongs in the selector labels? Only stable values such as name and instance. A version or chart version in there breaks the next upgrade with field is immutable.

Enterprise Note

  • The app.kubernetes.io/* labels are a Kubernetes convention; dashboards, cost tools and policies (e.g. “every Deployment needs team”) build on them.
  • Building blocks shared by many charts belong in a library chart (Day 10) instead of copied _helpers.tpl files.
  • Names and selectors are part of a chart’s interface. Changing them is a major release with a migration note.