Tag 5: Whitespace, Kontrollstrukturen und Scope
Ziel: Templates schreiben, die sauberes YAML erzeugen – mit
{{-,nindent,if,withundrange– und ein optionaler Ingress mit mehreren Hosts über Traefik. · Dauer: ca. 75 min · Voraussetzung: Tag 4
Briefing
- Eine Action lässt ihre Zeile stehen, auch wenn sie nichts ausgibt.
{{-frisst den Leerraum links samt Zeilenumbruch,-}}den rechts. - Falsch sind
false,0,"",nullund leere Listen oder Maps. Das trifft auch eine bewusst gesetzte0. withundrangesetzen den Punkt um. Zur Wurzel kommst du immer mit$.- Heute wächst
notesauf 0.4.0: Ressourcen, optionales Team-Label, nodeSelector und ein Ingress, denprod.yamleinschaltet.
curl -H 'Host: notes.lab' localhost ──> Traefik :80 ──> Ingress notes-api
├─ notes.lab
└─ api.notes.lab ──> svc :80
Drill 1: Leerzeilen sichtbar machen
Wie in Tag 4 arbeitest du auf einer Spielwiese, die am Ende wieder
verschwindet. cat -A zeigt jedes Zeilenende als
$.
# auf prod
mkdir -p ~/helm/tag05 && cd ~/helm/charts
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: ws
labels:
app: notes
{{ if .Values.team }}
team: {{ .Values.team }}
{{ end }}
data:
x: "1"
EOF
helm template notes ./notes -s templates/spielwiese.yaml --set team=plattform \
| cat -A | sed -n '8,12p'Erwartet:
app: notes$
$
team: plattform$
$
data:$
Die Zeilen mit if und end bleiben als
Leerzeilen mit vier Leerzeichen stehen. Das YAML ist noch gültig, aber
unordentlich – und in Listen oder Blöcken bricht es. Mit Minus links
verschwinden sie:
# auf prod
sed -i 's/{{ if/{{- if/; s/{{ end/{{- end/' notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml --set team=plattform \
| sed -n '8,11p'
helm template notes ./notes -s templates/spielwiese.yaml | sed -n '8,10p'Erwartet:
app: notes
team: plattform
data:
x: "1"
app: notes
data:
x: "1"
{{- frisst den Umbruch vor der Action
und die Einrückung davor. Übrig bleibt genau die Zeile, die du sehen
willst.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Ein Minus zu viel
# auf prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: ws
labels:
app: {{- .Chart.Name -}}
tier: backend
data:
x: "1"
EOF
helm template notes ./notes -s templates/spielwiese.yaml | sed -n '7,9p'Erwartet:
labels:
app:notestier: backend
data:
Das linke Minus frisst das Leerzeichen nach app:, das
rechte den Umbruch vor tier. Heraus kommt ein einziges
Label mit dem Schlüssel app:notestier – gültiges YAML,
darum meldet helm template keinen Fehler. Erst die API
lehnt den Label-Namen ab. Rechts ein Minus nur, wenn du die nächste
Zeile wirklich ankleben willst.
Fortschritt speichern? Kostenlos registrieren
Drill 3: Blöcke mit toYaml und nindent
Ganze Strukturen wie resources reichst du mit
toYaml durch. Das Deployment bekommt Ressourcen, ein
optionales Team-Label und einen optionalen nodeSelector:
# auf prod
cat > notes/templates/deployment.yaml <<'EOF'
{{/* notes/templates/deployment.yaml – Stand Tag 05 */}}
apiVersion: apps/v1
kind: Deployment
metadata:
name: notes-api
labels:
app.kubernetes.io/name: notes-api
{{- with .Values.team }}
team: {{ . | quote }}
{{- end }}
spec:
replicas: {{ hasKey .Values "replicaCount" | ternary .Values.replicaCount 2 }}
selector:
matchLabels: {app.kubernetes.io/name: notes-api}
template:
metadata:
labels:
app.kubernetes.io/name: notes-api
{{- with .Values.team }}
team: {{ . | quote }}
{{- end }}
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/values.yaml <<'EOF'
# notes/values.yaml – Stand Tag 05
# -- Anzahl der notes-api-Pods (0 ist erlaubt, null = Standard 2)
replicaCount: 2
image:
# -- Image ohne Tag
repository: ghcr.io/thomaszachmann/notes-api
# -- Tag des Images
tag: "0.7.1"
# -- API-Key (nur Labor! Ab Tag 8 aus einem Secret)
apiKey: lab-key-123
# -- Zusätzliche Umgebungsvariablen: Name -> Wert (Map, damit -f ergänzen kann)
env:
NOTES_LOG_LEVEL: info
NOTES_PAGE_SIZE: "50"
# -- Team-Label an Deployment und Pods (leer = kein Label)
team: ""
# -- Ressourcen des Containers
resources:
requests:
cpu: 20m
memory: 32Mi
limits:
memory: 128Mi
# -- nodeSelector der Pods (leer = keiner)
nodeSelector: {}
service:
# -- Port des Service
port: 80
ingress:
# -- Ingress anlegen
enabled: false
# -- IngressClass (k3s: traefik)
className: traefik
# -- Hostnamen, alle zeigen auf notes-api
hosts: []
EOF
sed -i 's/^version: .*/version: 0.4.0/; s/Tag 04/Tag 05/' notes/Chart.yaml
helm template notes ./notes -s templates/deployment.yaml | grep -A5 'resources:'Erwartet:
resources:
limits:
memory: 128Mi
requests:
cpu: 20m
memory: 32Mi
nindent 12 beginnt mit einem Zeilenumbruch und rückt
jede Zeile um 12 Stellen ein. Die Zahl ist die Einrückung des Blocks in
der Zieldatei. Zum Vergleich indent:
# auf prod
cp notes/templates/deployment.yaml ~/helm/tag05/deployment.bak
sed -i '/resources | nindent/s/{{- \(.*\) nindent/{{ \1 indent/' \
notes/templates/deployment.yaml
grep 'indent 12' notes/templates/deployment.yaml
helm template notes ./notes -s templates/deployment.yaml --debug 2>&1 \
| grep -A3 'resources:'
cp ~/helm/tag05/deployment.bak notes/templates/deployment.yamlErwartet:
{{ toYaml .Values.resources | indent 12 }}
resources:
limits:
memory: 128Mi
requests:
indent rückt auch die erste Zeile ein – zusätzlich zu
den Leerzeichen, die schon vor der Action stehen. Mit
nindent und {{- steht die Action links bündig
lesbar im Template, und das Ergebnis beginnt sauber in einer neuen
Zeile.
Fortschritt speichern? Kostenlos registrieren
Drill 4: Wenn 0 falsch ist
replicaCount: 0 ist eine legitime Wahl, etwa für eine
Wartung. default sieht das anders:
# auf prod
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: ws
data:
mitDefault: {{ .Values.replicaCount | default 2 | quote }}
hasKey: {{ hasKey .Values "replicaCount" | ternary .Values.replicaCount 2 | quote }}
art: {{ kindOf .Values.replicaCount | quote }}
istNull: {{ kindIs "invalid" .Values.replicaCount | quote }}
EOF
for s in replicaCount=0 replicaCount=null; do echo "== $s"
helm template notes ./notes -s templates/spielwiese.yaml --set $s | tail -5; doneErwartet:
== replicaCount=0
mitDefault: "2"
hasKey: "0"
art: "int64"
istNull: "false"
== replicaCount=null
mitDefault: "2"
hasKey: "2"
art: "invalid"
istNull: "true"
default ersetzt jeden falschen Wert, also auch 0.
hasKey fragt, ob der Schlüssel existiert –
null hat ihn in Tag 3 gelöscht, eine 0 nicht.
kindIs "invalid" erkennt null. Das Deployment
aus Drill 3 nutzt darum hasKey … | ternary.
# auf prod
helm template notes ./notes -s templates/deployment.yaml --set replicaCount=0 \
| yq .spec.replicasErwartet: 0
Fortschritt speichern? Kostenlos registrieren
Drill 5: if, and, eq und with
with prüft auf leer und setzt den Punkt
auf den Wert. Das ist die saubere Form für optionale Blöcke wie
Team-Label und nodeSelector:
# auf prod
helm template notes ./notes -s templates/deployment.yaml --set team=plattform \
--set 'nodeSelector.kubernetes\.io/hostname=prod' | grep -E -A1 'team|nodeSelector'Erwartet:
team: "plattform"
spec:
--
team: "plattform"
spec:
--
nodeSelector:
kubernetes.io/hostname: prod
Der Punkt im Schlüssel braucht bei --set einen
Backslash. Ohne Werte erscheinen weder Label noch
nodeSelector: – keine leeren Schlüssel, die Kubernetes
verwirren. Vergleiche sind Funktionen und stehen vorne: eq,
ne, lt, gt, and,
or, not. Du brauchst sie gleich beim
Ingress.
Fortschritt speichern? Kostenlos registrieren
Drill 6: range, $ und Variablen
# auf prod
cat > notes/templates/spielwiese.yaml <<'EOF'
{{- $mitGleich := 0 }}
{{- $mitDoppelpunkt := 0 }}
{{- range .Values.ingress.hosts }}
{{- $mitGleich = add1 $mitGleich }}
{{- $mitDoppelpunkt := add1 $mitDoppelpunkt }}
{{- end }}
apiVersion: v1
kind: ConfigMap
metadata:
name: ws
data:
mitGleich: {{ $mitGleich | quote }}
mitDoppelpunkt: {{ $mitDoppelpunkt | quote }}
{{- range $i, $h := .Values.ingress.hosts }}
host{{ $i }}: {{ $h }}.{{ $.Release.Namespace }}
{{- end }}
{{- range .Values.ingress.hosts }}
ohneDollar: {{ . }}.{{ .Release.Namespace }}
{{- end }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml -n notes \
--set 'ingress.hosts={notes.lab,api.notes.lab,www.notes.lab}'Erwartet:
Error: notes/templates/spielwiese.yaml:18:33
executing "notes/templates/spielwiese.yaml" at <.Release.Namespace>:
can't evaluate field Release in type interface {}
In range ist der Punkt der aktuelle Host, ein String.
Ein String hat kein .Release. Du löschst die letzten drei
Zeilen (die zweite Schleife) und renderst noch einmal:
# auf prod
head -n -3 notes/templates/spielwiese.yaml > ~/helm/tag05/sw.yaml
mv ~/helm/tag05/sw.yaml notes/templates/spielwiese.yaml
tail -3 notes/templates/spielwiese.yaml
helm template notes ./notes -s templates/spielwiese.yaml -n notes \
--set 'ingress.hosts={notes.lab,api.notes.lab,www.notes.lab}' | sed -n '7,$p'Erwartet:
{{- range $i, $h := .Values.ingress.hosts }}
host{{ $i }}: {{ $h }}.{{ $.Release.Namespace }}
{{- end }}
data:
mitGleich: "3"
mitDoppelpunkt: "0"
host0: notes.lab.notes
host1: api.notes.lab.notes
host2: www.notes.lab.notes
$ zeigt immer auf die Wurzel.
range $i, $h := … gibt Index und Element eigene Namen.
:= legt eine Variable an, = weist neu zu: Das
:= in der Schleife erzeugt bei jedem Durchlauf eine neue,
lokale Variable – die äußere bleibt 0.
Fortschritt speichern? Kostenlos registrieren
Drill 7: Ein optionaler Ingress
Ein Ingress entsteht nur, wenn er eingeschaltet ist und Hosts hat. Für Traefik kommt eine Annotation dazu.
# auf prod
rm notes/templates/spielwiese.yaml
cat > notes/templates/ingress.yaml <<'EOF'
{{/* notes/templates/ingress.yaml – Stand Tag 05 */}}
{{- if and .Values.ingress.enabled .Values.ingress.hosts }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: notes-api
{{- 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: notes-api
port:
number: {{ $.Values.service.port }}
{{- end }}
{{- end }}
EOF
helm template notes ./notes -s templates/ingress.yaml --set ingress.enabled=true
cat > values/prod.yaml <<'EOF'
# values/prod.yaml – Stand Tag 05
replicaCount: 2
team: plattform
env:
NOTES_LOG_LEVEL: warn
ingress:
enabled: true
hosts:
- notes.lab
- api.notes.lab
EOF
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | grep REVISION
kubectl -n notes get ingressErwartet:
Error: could not find template templates/ingress.yaml in chart
REVISION: 13
NAME CLASS HOSTS ADDRESS PORTS AGE
notes-api traefik notes.lab,api.notes.lab 172.16.0.123 80 5s
Ohne Hosts rendert die Datei leer – die Meldung kennst du aus Tag 1. Traefik lauscht über den ServiceLB von k3s auf Port 80 der VM. Den Hostnamen gibst du per Header mit:
# auf prod
curl -s -H 'Host: notes.lab' localhost/healthz
curl -s -H 'Host: api.notes.lab' 172.16.0.123/version; echo
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: falsch.lab' localhost/healthzErwartet:
ok
0.7.1
404
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Rendere das Deployment mit Team
webund zeig nur die Labels. Zeitziel: 30 s - Zeig alle Hosts des Ingress im Cluster in einer Zeile. Zeitziel: 30 s
- Rendere das Deployment für arm64-Nodes und zeig den nodeSelector. Zeitziel: 45 s
- Zeig Team-Label und Memory-Limit des laufenden Deployments. Zeitziel: 45 s
Lösung
# auf prod
helm template notes ./notes -s templates/deployment.yaml --set team=web \
| yq .metadata.labels
kubectl -n notes get ingress notes-api -o jsonpath='{.spec.rules[*].host}{"\n"}'
helm template notes ./notes -s templates/deployment.yaml \
--set 'nodeSelector.kubernetes\.io/arch=arm64' | yq .spec.template.spec.nodeSelector
kubectl -n notes get deploy notes-api -o yaml \
| yq '.metadata.labels.team,
.spec.template.spec.containers[0].resources.limits.memory'Erwartet:
app.kubernetes.io/name: notes-api
team: "web"
notes.lab api.notes.lab
kubernetes.io/arch: arm64
plattform
128Mi
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
# auf prod
helm list -n notesErwartet: Revision 13, notes-0.4.0,
deployed.
# auf prod
curl -s -H 'Host: notes.lab' localhost/healthzErwartet: ok
# auf prod
ls notes/templatesErwartet:
NOTES.txt configmap.yaml deployment.yaml ingress.yaml service.yaml
Challenge
Ein Host soll optional eigene Pfade bekommen: Ein Eintrag in
ingress.hosts ist entweder ein String (Pfad /)
oder eine Map mit name und paths. Probiere es
in einer Kopie des Charts mit tag05.lab und
api.tag05.lab (nur /notes und
/healthz) live aus.
Hinweis: kindIs "map" . unterscheidet
die beiden Formen, list "/" ist der Standard.
Lösung
# auf prod
cd ~/helm/tag05
cp -r ~/helm/charts/notes .
cat > notes/templates/ingress.yaml <<'EOF'
{{/* notes/templates/ingress.yaml – Challenge Tag 05 */}}
{{- if and .Values.ingress.enabled .Values.ingress.hosts }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: notes-api
spec:
{{- with .Values.ingress.className }}
ingressClassName: {{ . }}
{{- end }}
rules:
{{- range .Values.ingress.hosts }}
{{- $host := . }}
{{- $paths := list "/" }}
{{- if kindIs "map" . }}
{{- $host = .name }}
{{- $paths = .paths }}
{{- end }}
- host: {{ $host | quote }}
http:
paths:
{{- range $paths }}
- path: {{ . }}
pathType: Prefix
backend:
service:
name: notes-api
port:
number: {{ $.Values.service.port }}
{{- end }}
{{- end }}
{{- end }}
EOF
cat > hosts.yaml <<'EOF'
ingress:
enabled: true
hosts:
- tag05.lab
- name: api.tag05.lab
paths: [/notes, /healthz]
EOF
helm template notes ./notes -s templates/ingress.yaml -f hosts.yaml \
| yq -o json -I0 '[.spec.rules[] | {"h": .host, "p": [.http.paths[].path]}]'
helm install challenge ./notes -n tag05 --create-namespace -f hosts.yaml \
--set replicaCount=1 --wait | grep STATUS
curl -s -H 'Host: api.tag05.lab' localhost/healthz
curl -s -o /dev/null -w '%{http_code}\n' -H 'Host: api.tag05.lab' localhost/version
curl -s -H 'Host: tag05.lab' localhost/version; echoErwartet:
[{"h":"tag05.lab","p":["/"]},{"h":"api.tag05.lab","p":["/notes","/healthz"]}]
STATUS: deployed
ok
404
0.7.1
In der inneren Schleife ist der Punkt der Pfad – der Port kommt darum
über $. Die Variablen $host und
$paths werden mit := angelegt und mit
= im if überschrieben; mit := im
if wären sie danach wieder die alten.
Fortschritt speichern? Kostenlos registrieren
Aufräumen
# auf prod
helm uninstall challenge -n tag05
kubectl delete namespace tag05
cd ~/helm/charts
git add -A
git commit -qm "Tag 05: Whitespace, if/with/range, Ingress, notes 0.4.0"Erwartet:
release "challenge" uninstalled
namespace "tag05" deleted
Interview-Notiz
- Warum
nindentstattindent?nindentbeginnt mit einem Umbruch; zusammen mit{{-steht die Action lesbar am Zeilenanfang und der Block beginnt sauber in einer neuen Zeile. - if oder with? Beide prüfen auf leer.
withsetzt zusätzlich den Punkt auf den Wert; an.Releasekommst du darin nur noch über$. - Was tust du, wenn eine 0 als Wert erlaubt sein soll? Nicht
default, sondernhasKeyoderkindIsprüfen –defaultbehandelt 0 undfalsewie „nicht gesetzt“.
Enterprise-Notiz
- Leerzeilen und falsche Einrückung fallen oft erst bei der API auf –
oder gar nicht, wie
app:notestier. Darumkubeconformund Unit-Tests in CI (Tag 17). rangeüber Maps ist sortiert. Das hält Renderings stabil, sonst zeigt jedeshelm diffPhantom-Änderungen.- Ingress-Klassen und Annotationen unterscheiden sich je Controller; Charts machen sie über Werte einstellbar und setzen nur für den Standard-Controller etwas fest.
- Viele Plattformen ziehen von Ingress auf die Gateway API um
(
HTTPRoute). Ein Chart kann beides anbieten und mit.Capabilitieswählen (Tag 4).