Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 7: Sprig, required, tpl und lookup

Ziel: Die Funktionen beherrschen, mit denen fast jedes Chart auskommt – und wissen, wann lookup, Zufall und Prüfsummen das Verhalten eines Upgrades ändern. · Dauer: ca. 60 min · Voraussetzung: Tag 6

Briefing

  • Helm bringt die Sprig-Bibliothek mit: default, coalesce, printf, ternary, sha256sum, b64enc und rund 200 weitere. Ein Dutzend davon brauchst du ständig.
  • required und fail lassen das Rendern mit deiner Meldung abbrechen – lieber laut beim Deployment als still zur Laufzeit.
  • tpl rendert einen Wert als Template, lookup liest beim Rendern aus dem Cluster.
  • Alles, was sich bei jedem Rendern ändert (Zufall, Zeit, Cluster-Zustand), ändert auch jedes Upgrade.

Drill 1: Sprig-Rundgang

# auf 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'

Erwartet:

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 nimmt den ersten nicht leeren Wert, default ist der Sonderfall mit genau einem Kandidaten. int vor gt ist kein Schmuck: Aus values.yaml kommt 2 als float64, aus --set als int64 (Tag 2 und 5) – gt vergleicht nur gleiche Typen. semverCompare braucht das -0, sonst fallen Vorabversionen wie v1.36.4-gke.1043002 durch.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Das Image-Tag-Muster

Der Image-Tag soll standardmäßig der appVersion folgen. Dann reicht ein Versionssprung in Chart.yaml, und values.yaml bleibt unberührt.

# auf 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

Erwartet:

          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

required gibt den Wert zurück, wenn er da ist, und bricht sonst ab. null per --set löscht den Standard (Tag 3) – genau der Fall, den required fangen soll.

Fortschritt speichern? Kostenlos registrieren

Drill 3: Prüfsumme startet Pods neu

Ändert sich nur eine ConfigMap, laufen die alten Pods mit den alten Umgebungsvariablen weiter. Darum ziehen die Variablen aus env in eine eigene ConfigMap, und deren Prüfsumme kommt ins Pod-Template.

# auf 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

Erwartet:

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

Jetzt der Nachweis: zweimal dasselbe Upgrade, dann eines mit geänderter Konfiguration.

# auf 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

Erwartet (gekürzt):

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 ändert nichts, die Pods bleiben. Revision 17 ändert die ConfigMap, damit die Prüfsumme und damit das Pod-Template: Kubernetes rollt neu aus. Die Prüfsumme bewusst über config.yaml bilden, nicht über configmap.yaml – dort steht .Release.Revision, die Pods würden bei jedem Upgrade neu starten.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Zufall im Template

Ein Chart, das ein Datenbank-Passwort selbst erzeugt – im Wegwerf-Namespace:

# auf 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

Erwartet:

STATUS: deployed
sHQuF7plIMAZlkwJ
REVISION: 2
u21UJdNnbx4hmDPu

Jedes Upgrade würfelt neu. Eine Datenbank, die mit dem ersten Passwort initialisiert wurde, lässt die Anwendung danach nicht mehr herein.

Fortschritt speichern? Kostenlos registrieren

Drill 5: lookup behält das Passwort

# auf 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

Erwartet:

REVISION: 3
u21UJdNnbx4hmDPu
REVISION: 4
u21UJdNnbx4hmDPu

lookup nimmt apiVersion, Kind, Namespace und Name (leerer Name = Liste). Jetzt die Grenze: Ohne Cluster-Zugriff ist das Ergebnis leer.

# auf 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

Erwartet:

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 und --dry-run=client fragen den Cluster nicht – lookup liefert eine leere Map, das Template würfelt. Nur --dry-run=server zeigt, was wirklich ankäme. Seit Helm 4.3 schreibt --debug eine Log-Zeile, wenn lookup nichts findet. Werkzeuge, die mit helm template rendern (Argo CD, Tag 18), sehen immer den leeren Fall – das Template muss damit funktionieren.

Fortschritt speichern? Kostenlos registrieren

Drill 6: required und fail

required prüft einen Wert, fail eine Regel. Hier: nur bekannte Log-Level.

# auf 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

Erwartet:

  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…

Das Upgrade scheitert vor dem ersten API-Aufruf, es entsteht keine Revision. Achte auf den Ort: Die Meldung nennt deployment.yaml:18:28, nicht config.yaml – dort steht das include für die Prüfsumme, und das hat config.yaml zuerst gerendert. Morgen übernimmt ein Schema diese Prüfung, mit allen Fehlern auf einmal.

Fortschritt speichern? Kostenlos registrieren

Drill 7: tpl und Dauer-Funktionen

Hostnamen sollen vom Release-Namen abhängen. In values.yaml ist {{ … }} nur Text, erst tpl macht ein Template daraus.

# auf 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:

Erwartet:

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

tpl braucht als zweites Argument den Kontext – in der range-Schleife ist das $. Neu in Helm 4.3 sind Funktionen für Go-Dauern wie 30s oder 1m30s:

# auf 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

Erwartet:

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

Zwei Fallen: Das alte Sprig-duration versteht nur int64 und Strings – 90 aus einer Werte-Datei ist float64 und wird still zu 0s. Und env/expandenv fehlen absichtlich: Ein Chart soll nicht davon abhängen, auf welchem Rechner es gerendert wird. Die Dauer-Funktion kommt jetzt ins Chart:

# auf 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"}'

Erwartet:

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

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

  1. Zeig die ersten 16 Zeichen der Prüfsumme im laufenden Deployment. Zeitziel: 30 s
  2. Welche Hosts bekäme ein Release demo mit prod.yaml? Zeitziel: 20 s
  3. Lass das Rendern mit Log-Level trace scheitern, nur die Meldung. Zeitziel: 20 s
  4. Lies das Klartext-Passwort von g1 aus dem Cluster. Zeitziel: 20 s

Lösung

# auf 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

Erwartet:

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

Die Prüfsumme ist dieselbe wie in Revision 15: gleiche Konfiguration, gleicher Hash.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

# auf prod
helm list -n notes

Erwartet: Revision 18, notes-0.6.0, deployed.

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

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

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

Erwartet: 0.7.1

Challenge

Erweitere in einer Kopie den Image-Baustein um image.digest: Ist er gesetzt, lautet das Image repository@sha256:… und schlägt den Tag; ein Digest, der nicht mit sha256: beginnt, lässt das Rendern scheitern. Installiere den Release chal per Digest in tag07 und weise den Digest am laufenden Pod nach.

Hinweis: with setzt den Punkt um – den Chart-Kontext erreichst du darin über $.

Lösung

# auf 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"}'

Erwartet (Digest gekürzt):

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…

Ein Digest ist unveränderlich, ein Tag nicht. Darum pinnen viele Produktions-Charts per Digest – lesbar bleibt es, wenn der Tag zusätzlich in appVersion steht.

Fortschritt speichern? Kostenlos registrieren

Aufräumen

# auf 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"

Erwartet:

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

Interview-Notiz

  • Wie startest du Pods neu, wenn sich eine ConfigMap ändert? Mit einer Prüfsummen-Annotation im Pod-Template (include … | sha256sum). Neuer Hash, neues Pod-Template, Rolling Update.
  • Was macht lookup, und wo sind die Grenzen? Es liest beim Rendern Objekte aus dem Cluster, etwa ein bestehendes Passwort. Bei helm template, --dry-run=client und in Argo CD ist es leer – das Template muss den leeren Fall vertragen.
  • Warum gibt es env in Helm nicht? Das Rendering soll nur von Chart und Werten abhängen, nicht vom Rechner, auf dem es läuft.

Enterprise-Notiz

  • Selbst erzeugte Passwörter per lookup sind ein Notbehelf. In Produktion kommen Geheimnisse von außen (Tag 8, Tag 16), das Chart verweist nur darauf.
  • Prüfsummen-Annotationen gehören an jede ConfigMap und jedes Secret, das als Umgebung oder Datei in Pods landet – sonst laufen Pods tagelang mit alter Konfiguration.
  • fail-Regeln sind gut für Abhängigkeiten zwischen Werten („TLS braucht ein Secret“); reine Typ- und Wertebereichsprüfungen gehören ins Schema.
  • Pipelines rendern mit --dry-run=server, wenn das Chart lookup nutzt – sonst vergleicht der Diff mit einem Zustand, den es nie geben wird.