Tag 6: Bausteine – define, include, _helpers.tpl {#tag06}
Ziel: Namen und Labels einmal in
_helpers.tpldefinieren und überall mitincludenutzen – und die typischen Fehler kennen, die Bausteine gefährlich machen. · Dauer: ca. 45 min · Voraussetzung: Tag 5
Briefing
definelegt ein benanntes Template an,includeruft es auf und gibt einen String zurück, den du mitnindentweiterverarbeitest.- Der Punkt am Ende von
include "notes.labels" .gibt den Kontext mit. Ohne ihn hat der Baustein nichts, womit er arbeiten kann. - Benannte Templates sind global über Chart und
Subcharts. Darum immer mit Chart-Präfix:
notes.fullname, niefullname. - Selektor-Labels dürfen sich nach der Installation nie ändern. Darum
gibt es zwei Bausteine:
notes.selectorLabels(stabil) undnotes.labels(alles).
_helpers.tpl deployment.yaml, service.yaml, ...
├─ notes.name (Basis für die drei darunter)
├─ notes.fullname ──include──> metadata.name
├─ notes.selectorLabels ──include──> spec.selector / Service-Selector
└─ notes.labels ──include──> metadata.labels und Pod-Labels
Drill 1: _helpers.tpl anlegen
# auf 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'Erwartet:
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: {}
Enthält der Release-Name schon den Chart-Namen, nimmt
notes.fullname nur den Release-Namen – sonst hieße alles
notes-notes. {{- define … -}} mit beidseitigem
Minus ist hier richtig: Ein Baustein soll weder Leerzeilen davor noch
danach liefern. replace "+" "_" macht aus einer Version wie
1.0.0+build.7 ein gültiges Label.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Wozu trunc 63?
Viele Kubernetes-Namen sind DNS-Labels und dürfen höchstens 63 Zeichen haben.
# auf 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'Erwartet:
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
Release-Namen begrenzt Helm selbst auf 53 Zeichen.
trunc 63 schützt vor langen Chart-Namen und
fullnameOverride. Aber Achtung: Das -test
kommt nach dem Kürzen – 68 Zeichen. Für eine ConfigMap
egal (bis 253 erlaubt), für einen Service nicht. Die Challenge baut
einen Baustein, der das richtig macht.
Fortschritt speichern? Kostenlos registrieren
Drill 3: Alle Templates umstellen
# auf 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 }}
EOFConfigMap und Ingress bekommen Name und Labels ebenfalls. Im Ingress
steht der Service-Name in einer range-Schleife – dort ist
der Kontext $:
# auf 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:'Erwartet:
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
Jetzt das Upgrade. Aus notes-api wird
notes:
# auf 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/healthzErwartet:
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
Ein neuer Name ist für Kubernetes ein neues Objekt: Helm legt
notes an und löscht notes-api, weil es im
neuen Manifest fehlt. In Produktion heißt das eine kurze Lücke – Namen
legst du darum früh fest.
Fortschritt speichern? Kostenlos registrieren
Drill 4: Den Punkt vergessen
# auf 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.yamlErwartet:
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
Ohne Kontext verweigert include gleich den Dienst. Mit
dem falschen Kontext läuft der Baustein los und sucht
.Values.fullnameOverride in .Values – also
.Values.Values.fullnameOverride. Die Meldung zeigt Datei,
Zeile und Spalte im Helper.
Fortschritt speichern? Kostenlos registrieren
Drill 5: template oder include?
# auf 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.yamlErwartet:
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 ist eine Anweisung, keine Funktion: Es schreibt
direkt in die Ausgabe und kann nicht in eine Pipe. Ohne
nindent rückt es nur die erste Zeile ein – die zweite
landet am Rand und wird zu einem Feld auf oberster Ebene. Darum
praktisch immer include.
Fortschritt speichern? Kostenlos registrieren
Drill 6: Kollision globaler Namen
Zwei Charts, beide definieren fullname ohne Präfix – ein
Eltern-Chart und ein Subchart in charts/ (mehr dazu in Tag
9):
# auf 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 configmapErwartet:
# 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
Die Definition des Eltern-Charts überschreibt die des Subcharts.
Beide ConfigMaps heißen gleich, und Helm 4 installiert ohne Fehler – am
Ende gibt es nur eine ConfigMap aus dem Chart.
kube-root-ca.crt legt Kubernetes in jedem Namespace selbst
an. Ihr Alter hängt davon ab, wann tag06 entstand –
--create-namespace legt ihn nur an, wenn er fehlt. Mit
Präfix ist der Spuk vorbei:
# auf 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:'Erwartet:
release "x" uninstalled
name: kind-x
name: eltern-x
Fortschritt speichern? Kostenlos registrieren
Drill 7: Version im Selektor
Was passiert, wenn jemand die Version in die Selektor-Labels schreibt? Du probierst es an einer Kopie:
# auf 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'Erwartet:
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
spec.selector eines Deployments ist unveränderlich. Mit
der Version darin scheitert das erste Upgrade auf eine neue App-Version.
Wie du einen Release aus diesem Zustand holst, zeigt Tag 19.
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Wie heißt der Service, wenn der Release
shopheißt? Zeitziel: 20 s - Zeig den Selektor des laufenden Deployments
notes. Zeitziel: 20 s - Zeig alle Objekte des Releases
notesüber das Instance-Label. Zeitziel: 30 s - Liste alle benannten Templates in
_helpers.tpl. Zeitziel: 15 s
Lösung
# auf 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.tplErwartet:
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"
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
# auf prod
helm list -n notesErwartet: Revision 14, notes-0.5.0,
deployed.
# auf prod
kubectl -n notes get deploy notes -o jsonpath='{.metadata.labels.helm\.sh/chart}{"\n"}'Erwartet: notes-0.5.0
# auf prod
curl -s -H 'Host: api.notes.lab' localhost/version; echoErwartet: 0.7.1
Challenge
Baue in einer Kopie einen Baustein notes.componentName,
der einen vollständigen Namen mit Suffix liefert und dabei garantiert
höchstens 63 Zeichen lang ist – ohne das Suffix abzuschneiden. Nutze ihn
für die ConfigMap (-info) und teste mit einem 70 Zeichen
langen fullnameOverride.
Hinweis: Ein Baustein bekommt nur ein Argument.
Mehrere packst du mit dict in eine Map.
Lösung
# auf 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)'Erwartet:
notes-info
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-info
63
dict "ctx" . "suffix" "info" baut eine Map; im Baustein
ist der Punkt diese Map, darum .ctx und
.suffix. Die Basis wird auf 62 - len(suffix)
gekürzt, dann kommen Bindestrich und Suffix dazu. Ein naives
printf … | trunc 63 hätte das -info
abgeschnitten – und die ConfigMaps -info,
-config und -files der nächsten Tage hießen
alle gleich.
Fortschritt speichern? Kostenlos registrieren
Aufräumen
# auf 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"Erwartet:
release "sel" uninstalled
namespace "tag06" deleted
Interview-Notiz
- Warum
includestatttemplate?includegibt einen String zurück, den du mitnindenteinrückst.templateschreibt direkt in die Ausgabe und kann nicht in eine Pipe. - Warum ein Chart-Präfix bei benannten Templates? Sie sind global über alle Charts eines Releases. Gleiche Namen überschreiben sich still – inklusive gleich benannter Objekte.
- Was gehört in die Selektor-Labels? Nur stabile Werte wie
Name und Instanz. Version oder Chart-Version darin machen das nächste
Upgrade mit
field is immutablekaputt.
Enterprise-Notiz
- Die Labels
app.kubernetes.io/*sind Konvention von Kubernetes; Dashboards, Kostenwerkzeuge und Policies (z. B. „jedes Deployment brauchtteam“) bauen darauf. - Bausteine, die viele Charts teilen, gehören in ein Library Chart
(Tag 10) statt in kopierte
_helpers.tpl-Dateien. - Namen und Selektoren sind Teil der Schnittstelle eines Charts. Eine Änderung daran ist ein Major-Release mit Migrationshinweis.