Skip to content
Hands-on IT IT Drills

Day 7: Sprig, required, tpl and lookup

Goal: Master the functions almost every chart gets by with – and know when lookup, randomness and checksums change the behaviour of an upgrade. · Duration: approx. 60 min · Prerequisite: Day 6

Briefing

  • Helm ships with the Sprig library: default, coalesce, printf, ternary, sha256sum, b64enc and about 200 more. You need a dozen of them all the time.
  • required and fail abort rendering with your message – better loud at deployment time than silent at runtime.
  • tpl renders a value as a template, lookup reads from the cluster while rendering.
  • Anything that changes on every render (randomness, time, cluster state) also changes every upgrade.

Drill 1: A Sprig tour

# on prod
mkdir -p ~/helm/tag07 && cd ~/helm/charts
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: spiel
data:
  default: {{ .Values.region | default "eu-central" }}
  coalesce: {{ coalesce .Values.region .Values.team "ohne-team" }}
  printf: {{ printf "%s-%d" .Release.Name .Release.Revision }}
  ternary: {{ ternary "viele" "wenige" (gt (int .Values.replicaCount) 1) }}
  upper: {{ .Chart.Name | upper }}
  kube: {{ .Capabilities.KubeVersion.Version }}
  neu: {{ semverCompare ">=1.35.0-0" .Capabilities.KubeVersion.Version | quote }}
  b64: {{ .Values.apiKey | b64enc }}
  hash: {{ .Values.apiKey | sha256sum | trunc 12 }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml | sed -n '/^data:/,$p'
helm template notes ./notes -s templates/spielwiese.yaml --set team=plattform \
  --set replicaCount=1 --kube-version 1.34.0 | grep -E 'coalesce|ternary|kube|neu'

The German strings are simple: ohne-team means ‘no team’, viele and wenige mean ‘many’ and ‘few’, and the key neu means ‘new’.

Expected:

data:
  default: eu-central
  coalesce: ohne-team
  printf: notes-1
  ternary: viele
  upper: NOTES
  kube: v1.37.0
  neu: "true"
  b64: bGFiLWtleS0xMjM=
  hash: b2537f5cf4ce
  coalesce: plattform
  ternary: wenige
  kube: v1.34.0
  neu: "false"

coalesce takes the first non-empty value; default is the special case with exactly one candidate. The int before gt is not decoration: from values.yaml the 2 arrives as float64, from --set as int64 (Day 2 and Day 5) – gt only compares equal types. semverCompare needs the -0, otherwise pre-release versions such as v1.36.4-gke.1043002 fail the check.

Save your progress? Sign up for free

Drill 2: The image tag pattern

By default, the image tag should follow appVersion. Then a version bump in Chart.yaml is enough, and values.yaml stays untouched.

# on prod
rm notes/templates/spielwiese.yaml
cat >> notes/templates/_helpers.tpl <<'EOF'

{{/* Image: Tag leer = appVersion aus Chart.yaml */}}
{{- define "notes.image" -}}
{{- $repo := required "image.repository fehlt" .Values.image.repository }}
{{- printf "%s:%s" $repo (.Values.image.tag | default .Chart.AppVersion) }}
{{- end }}
EOF
sed -i 's/Stand Tag 06/Stand Tag 07/' notes/templates/_helpers.tpl
sed -i 's|image: ".*"|image: {{ include "notes.image" . \| quote }}|' \
  notes/templates/deployment.yaml
sed -i 's/^  tag: "0.7.1"/  tag: ""/' notes/values.yaml
sed -i 's/# -- Tag des Images/& (leer = appVersion)/' notes/values.yaml
helm template notes ./notes -s templates/deployment.yaml | grep 'image:'
helm template notes ./notes -s templates/deployment.yaml --set image.tag=0.7.0 \
  | grep 'image:'
helm template notes ./notes -s templates/deployment.yaml --set image.repository=null

The helper comment says ‘empty tag = appVersion from Chart.yaml’, and the doc comment for image.tag gets the same note (leer = appVersion).

Expected:

          image: "ghcr.io/thomaszachmann/notes-api:0.7.1"
          image: "ghcr.io/thomaszachmann/notes-api:0.7.0"
Error: execution error at (notes/templates/deployment.yaml:20:20): image.repository
fehlt

image.repository fehlt means ‘image.repository missing’. required returns the value if it is there and aborts otherwise. null via --set deletes the default (Day 3) – exactly the case required is meant to catch.

Save your progress? Sign up for free

Drill 3: A checksum restarts Pods

If only a ConfigMap changes, the old Pods keep running with the old environment variables. So the variables from env move into a ConfigMap of their own, and its checksum goes into the Pod template.

# on prod
cat > notes/templates/config.yaml <<'EOF'
{{/* notes/templates/config.yaml – Stand Tag 07 */}}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "notes.fullname" . }}-config
  labels:
    {{- include "notes.labels" . | nindent 4 }}
data:
  {{- range $name, $value := .Values.env }}
  {{ $name }}: {{ $value | quote }}
  {{- end }}
EOF
cat > notes/templates/deployment.yaml <<'EOF'
{{/* notes/templates/deployment.yaml – Stand Tag 07 */}}
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 }}
      annotations:
        checksum/config: {{ include (print $.Template.BasePath "/config.yaml") .
          | sha256sum }}
    spec:
      containers:
        - name: notes-api
          image: {{ include "notes.image" . | quote }}
          ports: [{name: http, containerPort: 8080}]
          env:
            - name: NOTES_API_KEY
              value: {{ .Values.apiKey | quote }}
          envFrom:
            - configMapRef:
                name: {{ include "notes.fullname" . }}-config
          readinessProbe:
            httpGet: {path: /healthz, port: http}
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
EOF
sed -i 's/^version: .*/version: 0.6.0/; s/Tag 06/Tag 07/' notes/Chart.yaml
sed -i 's/Stand Tag 06/Stand Tag 07/' notes/values.yaml
helm template notes ./notes -f values/prod.yaml -s templates/config.yaml \
  | sed -n '/^data/,$p'
helm template notes ./notes -f values/prod.yaml -s templates/deployment.yaml \
  | grep checksum

Expected:

data:
  NOTES_LOG_LEVEL: "warn"
  NOTES_PAGE_SIZE: "50"
        checksum/config: 6af1d3391f1e23f237f06c5c1c0b187835d5…

Now the proof: the same upgrade twice, then one with a changed configuration.

# on prod
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | grep REVISION
kubectl -n notes get pods -o name
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | grep REVISION
kubectl -n notes get pods -o name
helm upgrade notes ./notes -n notes -f values/prod.yaml \
  --set env.NOTES_PAGE_SIZE=25 --wait | grep REVISION
kubectl -n notes get pods

Expected (abridged):

REVISION: 15
pod/notes-5cbf98c65d-6jbsr
pod/notes-5cbf98c65d-qc5kq
REVISION: 16
pod/notes-5cbf98c65d-6jbsr
pod/notes-5cbf98c65d-qc5kq
REVISION: 17
NAME                     READY   STATUS      RESTARTS   AGE
notes-5cbf98c65d-6jbsr   0/1     Completed   0          14s
notes-6ddc7cf47c-nhdf2   1/1     Running     0          5s
notes-6ddc7cf47c-vvrbh   1/1     Running     0          4s

Revision 16 changes nothing, the Pods stay. Revision 17 changes the ConfigMap, therefore the checksum and therefore the Pod template: Kubernetes rolls out again. Build the checksum over config.yaml on purpose, not over configmap.yaml – that one contains .Release.Revision, so the Pods would restart on every upgrade.

Save your progress? Sign up for free

Drill 4: Randomness in a template

A chart (geheim, German for ‘secret’) that generates a database password itself – in a throwaway namespace:

# on prod
cd ~/helm/tag07
mkdir -p geheim/templates
printf 'apiVersion: v2\nname: geheim\nversion: 0.1.0\n' > geheim/Chart.yaml
cat > geheim/templates/secret.yaml <<'EOF'
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Release.Name }}-db
data:
  password: {{ randAlphaNum 16 | b64enc }}
EOF
helm install g1 ./geheim -n tag07 --create-namespace | grep STATUS
kubectl -n tag07 get secret g1-db -o jsonpath='{.data.password}' | base64 -d; echo
helm upgrade g1 ./geheim -n tag07 | grep REVISION
kubectl -n tag07 get secret g1-db -o jsonpath='{.data.password}' | base64 -d; echo

Expected:

STATUS: deployed
sHQuF7plIMAZlkwJ
REVISION: 2
u21UJdNnbx4hmDPu

Every upgrade rolls the dice again. A database that was initialised with the first password will not let the application in afterwards.

Save your progress? Sign up for free

Drill 5: lookup keeps the password

# on prod
cat > geheim/templates/secret.yaml <<'EOF'
{{- $alt := lookup "v1" "Secret" .Release.Namespace (printf "%s-db" .Release.Name) }}
{{- $pw := randAlphaNum 16 | b64enc }}
{{- if $alt }}
{{- $pw = index $alt.data "password" }}
{{- end }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ .Release.Name }}-db
data:
  password: {{ $pw }}
EOF
helm upgrade g1 ./geheim -n tag07 | grep REVISION
kubectl -n tag07 get secret g1-db -o jsonpath='{.data.password}' | base64 -d; echo
helm upgrade g1 ./geheim -n tag07 | grep REVISION
kubectl -n tag07 get secret g1-db -o jsonpath='{.data.password}' | base64 -d; echo

Expected:

REVISION: 3
u21UJdNnbx4hmDPu
REVISION: 4
u21UJdNnbx4hmDPu

$alt means ‘old’. lookup takes apiVersion, kind, namespace and name (empty name = list). Now the limit: without cluster access the result is empty.

# on prod
kubectl -n tag07 get secret g1-db -o jsonpath='{.data.password}'; echo
helm template g1 ./geheim -n tag07 | grep password
helm upgrade g1 ./geheim -n tag07 --dry-run=client | grep password
helm upgrade g1 ./geheim -n tag07 --dry-run=server | grep password
helm install g2 ./geheim -n tag07 --dry-run=server --debug 2>&1 | grep lookup

Expected:

dTIxVUpkTm5ieDRobURQdQ==
  password: bFB4bUxnMktjN1JTZ3RiRw==
  password: aU9tQmJzNDFiZnRWdmxzSQ==
  password: dTIxVUpkTm5ieDRobURQdQ==
level=DEBUG msg="lookup: resource not found" apiVersion=v1 kind=Secret namespace=tag07
name=g2-db

helm template and --dry-run=client do not ask the cluster – lookup returns an empty map, and the template rolls the dice. Only --dry-run=server shows what would really arrive. Since Helm 4.3, --debug logs a line when lookup finds nothing. Tools that render with helm template (Argo CD, Day 18) always see the empty case – the template has to work with it.

Save your progress? Sign up for free

Drill 6: required and fail

required checks a value, fail a rule. Here: only known log levels.

# on prod
cd ~/helm/charts
cat > notes/templates/config.yaml <<'EOF'
{{/* notes/templates/config.yaml – Stand Tag 07 */}}
{{- $level := .Values.env.NOTES_LOG_LEVEL | default "info" }}
{{- if not (has $level (list "debug" "info" "warn" "error")) }}
{{- fail (printf "NOTES_LOG_LEVEL %q: erlaubt sind debug, info, warn, error" $level) }}
{{- end }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ include "notes.fullname" . }}-config
  labels:
    {{- include "notes.labels" . | nindent 4 }}
data:
  {{- range $name, $value := .Values.env }}
  {{ $name }}: {{ $value | quote }}
  {{- end }}
EOF
helm template notes ./notes --set env.NOTES_LOG_LEVEL=debug -s templates/config.yaml \
  | grep LOG
helm upgrade notes ./notes -n notes -f values/prod.yaml --set env.NOTES_LOG_LEVEL=WARN
helm history notes -n notes --max 2

Expected:

  NOTES_LOG_LEVEL: "debug"
Error: UPGRADE FAILED: execution error at (notes/templates/deployment.yaml:18:28):
NOTES_LOG_LEVEL "WARN": erlaubt sind debug, info, warn, error
REVISION  UPDATED                   STATUS      CHART        APP VERSION  DESCRIPTION
16        Fri Nov 20 01:31:33 2026  superseded  notes-0.6.0  0.7.1        Upgrade compl…
17        Fri Nov 20 01:31:35 2026  deployed    notes-0.6.0  0.7.1        Upgrade compl…

The message reads ‘allowed are debug, info, warn, error’. The upgrade fails before the first API call, and no revision is created. Watch the location: the message names deployment.yaml:18:28, not config.yaml – that is where the include for the checksum sits, and it rendered config.yaml first. Tomorrow a schema takes over this check, with all errors at once.

Save your progress? Sign up for free

Drill 7: tpl and duration functions

Hostnames should depend on the release name. In values.yaml, {{ … }} is just text; only tpl turns it into a template.

# on prod
sed -i 's/- host: {{ . | quote }}/- host: {{ tpl . $ | quote }}/' \
  notes/templates/ingress.yaml
sed -i 's/Stand Tag 06/Stand Tag 07/' notes/templates/ingress.yaml
cat > values/prod.yaml <<'EOF'
# values/prod.yaml – Stand Tag 07
replicaCount: 2
team: plattform
env:
  NOTES_LOG_LEVEL: warn
ingress:
  enabled: true
  hosts:
    - "{{ .Release.Name }}.lab"
    - "api.{{ .Release.Name }}.lab"
EOF
helm template notes ./notes -f values/prod.yaml -s templates/ingress.yaml | grep host:
helm template shop ./notes -f values/prod.yaml -s templates/ingress.yaml | grep host:

Expected:

    - host: "notes.lab"
    - host: "api.notes.lab"
    - host: "shop.lab"
    - host: "api.shop.lab"

tpl needs the context as its second argument – inside the range loop that is $. New in Helm 4.3 are functions for Go durations such as 30s or 1m30s:

# on prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
  name: spiel
data:
  sekunden: {{ durationSeconds .Values.shutdownTimeout | quote }}
  minuten: {{ durationMinutes "90s" | quote }}
  gerundet: {{ durationRound "3h10m" | quote }}
  ausZahl: {{ duration .Values.sek | quote }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml --set shutdownTimeout=45s \
  --set sek=90 | sed -n '/^data/,$p'
echo 'sek: 90' > ~/helm/tag07/sek.yaml
helm template notes ./notes -s templates/spielwiese.yaml --set shutdownTimeout=45s \
  -f ~/helm/tag07/sek.yaml | grep ausZahl
echo '  env: {{ env "HOME" }}' >> notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml --set shutdownTimeout=1m \
  2>&1 | head -1
rm notes/templates/spielwiese.yaml

The keys mean ‘seconds’, ‘minutes’, ‘rounded’ and ‘from number’; sek is short for seconds.

Expected:

data:
  sekunden: "45"
  minuten: "1.5"
  gerundet: "3h"
  ausZahl: "1m30s"
  ausZahl: "0s"
Error: parse error at (notes/templates/spielwiese.yaml:10): function "env" not defined

Two traps: the old Sprig duration only understands int64 and strings – 90 from a values file is float64 and silently becomes 0s. And env/expandenv are missing on purpose: a chart should not depend on the machine it is rendered on. The duration function now goes into the chart:

# on prod
cat >> notes/values.yaml <<'EOF'

# -- Zeit zum sauberen Beenden (Go-Dauer wie 30s, 1m)
shutdownTimeout: 30s
EOF
G='      terminationGracePeriodSeconds: {{ durationSeconds .Values.shutdownTimeout }}'
sed -i "/^    spec:$/a\\$G" notes/templates/deployment.yaml
helm template notes ./notes -s templates/deployment.yaml | grep -B1 -A1 termination
helm lint notes | tail -1
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | grep REVISION
kubectl -n notes get deploy notes \
  -o jsonpath='{.spec.template.spec.terminationGracePeriodSeconds}{"\n"}'

The doc comment means ‘time for a clean shutdown (Go duration such as 30s, 1m)’.

Expected:

    spec:
      terminationGracePeriodSeconds: 30
      containers:
1 chart(s) linted, 0 chart(s) failed
REVISION: 18
30

Save your progress? Sign up for free

Exercise: Speed Drills

  1. Show the first 16 characters of the checksum in the running Deployment. Target time: 30 s
  2. Which hosts would a release demo get with prod.yaml? Target time: 20 s
  3. Make rendering fail with log level trace, message only. Target time: 20 s
  4. Read the plain-text password of g1 from the cluster. Target time: 20 s

Solution

# on prod
cd ~/helm/charts
kubectl -n notes get deploy notes \
  -o jsonpath='{.spec.template.metadata.annotations.checksum/config}' | cut -c1-16
helm template demo ./notes -f values/prod.yaml -s templates/ingress.yaml | grep host:
helm template notes ./notes --set env.NOTES_LOG_LEVEL=trace 2>&1 | head -1
kubectl -n tag07 get secret g1-db -o jsonpath='{.data.password}' | base64 -d; echo

Expected:

6af1d3391f1e23f2
    - host: "demo.lab"
    - host: "api.demo.lab"
Error: execution error at (notes/templates/deployment.yaml:18:28): NOTES_LOG_LEVEL
"trace": erlaubt sind debug, info, warn, error
u21UJdNnbx4hmDPu

The checksum is the same as in revision 15: same configuration, same hash.

Save your progress? Sign up for free

Checkpoint

# on prod
helm list -n notes

Expected: Revision 18, notes-0.6.0, deployed.

# on prod
kubectl -n notes get cm notes-config -o jsonpath='{.data}{"\n"}'

Expected: {"NOTES_LOG_LEVEL":"warn","NOTES_PAGE_SIZE":"50"}

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

Expected: 0.7.1

Challenge

In a copy, extend the image building block with image.digest: if it is set, the image becomes repository@sha256:… and beats the tag; a digest that does not start with sha256: makes rendering fail. Install the release chal by digest in tag07 and prove the digest on the running Pod.

Hint: with moves the dot – inside it you reach the chart context through $.

Solution

# on prod
cd ~/helm/tag07 && rm -rf notes && cp -r ~/helm/charts/notes .
cat > notes/templates/_image.tpl <<'EOF'
{{/* Image mit optionalem Digest: repo@sha256:… schlägt den Tag */}}
{{- define "notes.imageRef" -}}
{{- $repo := required "image.repository fehlt" .Values.image.repository }}
{{- with .Values.image.digest }}
{{- if not (hasPrefix "sha256:" .) }}
{{- fail (printf "image.digest %q muss mit sha256: beginnen" .) }}
{{- end }}
{{- printf "%s@%s" $repo . }}
{{- else }}
{{- printf "%s:%s" $repo ($.Values.image.tag | default $.Chart.AppVersion) }}
{{- end }}
{{- end }}
EOF
sed -i 's/include "notes.image"/include "notes.imageRef"/' \
  notes/templates/deployment.yaml
D=$(kubectl -n notes get pod -l app.kubernetes.io/name=notes \
  -o jsonpath='{.items[0].status.containerStatuses[0].imageID}' | cut -d@ -f2)
echo $D
helm template notes ./notes -s templates/deployment.yaml --set image.digest=$D \
  | grep image:
helm template notes ./notes -s templates/deployment.yaml --set image.digest=abc \
  2>&1 | head -1
helm install chal ./notes -n tag07 --set image.digest=$D --set replicaCount=1 --wait \
  | grep STATUS
kubectl -n tag07 get pod -l app.kubernetes.io/instance=chal \
  -o jsonpath='{.items[0].status.containerStatuses[0].imageID}{"\n"}'

Expected (digest abridged):

sha256:7913de48bede…
          image: "ghcr.io/thomaszachmann/notes-api@sha256:7913de48bede…"
Error: execution error at (notes/templates/deployment.yaml:24:20): image.digest "abc"
muss mit sha256: beginnen
STATUS: deployed
ghcr.io/thomaszachmann/notes-api@sha256:7913de48bede…

The error says the digest ‘must start with sha256:’. A digest is immutable, a tag is not. That is why many production charts pin by digest – it stays readable if the tag is also kept in appVersion.

Save your progress? Sign up for free

Cleanup

# on prod
helm uninstall chal g1 -n tag07
kubectl delete namespace tag07
cd ~/helm/charts
git add -A
git commit -qm "Tag 07: Sprig, required/fail, tpl, Prüfsumme, notes 0.6.0"

Expected:

release "chal" uninstalled
release "g1" uninstalled
namespace "tag07" deleted

Interview Note

  • How do you restart Pods when a ConfigMap changes? With a checksum annotation in the Pod template (include … | sha256sum). New hash, new Pod template, rolling update.
  • What does lookup do, and where are its limits? It reads objects from the cluster while rendering, for example an existing password. With helm template, --dry-run=client and in Argo CD it is empty – the template has to cope with the empty case.
  • Why is there no env in Helm? Rendering should depend only on the chart and the values, not on the machine it runs on.

Enterprise Note

  • Self-generated passwords via lookup are a stopgap. In production, secrets come from outside (Day 8, Day 16), and the chart only references them.
  • Checksum annotations belong on every ConfigMap and every Secret that ends up in Pods as environment or files – otherwise Pods run with old configuration for days.
  • fail rules are good for dependencies between values (“TLS needs a Secret”); pure type and range checks belong in the schema.
  • Pipelines render with --dry-run=server when the chart uses lookup – otherwise the diff compares against a state that will never exist.