Tag 8: Dateien, Secrets-Verweis und values.schema.json
Ziel: Konfigurationsdateien sauber ins Chart bringen, Geheimnisse nur noch per Verweis annehmen und die Werte des Charts mit einem JSON-Schema absichern. · Dauer: ca. 60 min · Voraussetzung: Tag 7
Briefing
- Lange Konfigurationen liegen als echte Dateien neben
templates/und kommen über.Filesins Chart. Was intemplates/liegt oder.helmignoreausschließt, ist für.Filesunsichtbar – ohne Fehlermeldung. - Das Chart liefert keine Geheimnisse aus, es verweist auf ein Secret,
das anders entsteht (
existingSecret-Muster). values.schema.jsonprüft alle Werte vor dem Rendern – beilint,template,installundupgrade, mit allen Fehlern auf einmal.
notes/
├─ config/*.conf, motd.txt ──.Files──> ConfigMap notes-files
├─ values.schema.json ──prüft───> Werte (vor dem Rendern)
└─ templates/deployment.yaml ──secretKeyRef──> Secret notes-api-key (kubectl)
Drill 1: Dateien mit Files.Glob und Files.Get
# auf prod
mkdir -p ~/helm/tag08 && cd ~/helm/charts
mkdir -p notes/config
cat > notes/config/limits.conf <<'EOF'
# notes/config/limits.conf – Stand Tag 08
max_note_length = 2000
max_notes_per_minute = 60
EOF
cat > notes/config/logging.conf <<'EOF'
# notes/config/logging.conf – Stand Tag 08
format = text
EOF
cat > notes/config/motd.txt <<'EOF'
Willkommen bei {{ .Release.Name }} im Namespace {{ .Release.Namespace }}.
EOF
cat > notes/templates/files.yaml <<'EOF'
{{/* notes/templates/files.yaml – Stand Tag 08 */}}
apiVersion: v1
kind: ConfigMap
metadata:
name: {{ include "notes.fullname" . }}-files
labels:
{{- include "notes.labels" . | nindent 4 }}
data:
{{- (.Files.Glob "config/*.conf").AsConfig | nindent 2 }}
motd.txt: |-
{{- tpl (.Files.Get "config/motd.txt") . | nindent 4 }}
EOF
helm template notes ./notes -s templates/files.yaml -n notes | sed -n '/^data/,$p'Erwartet:
data:
limits.conf: |
# notes/config/limits.conf – Stand Tag 08
max_note_length = 2000
max_notes_per_minute = 60
logging.conf: |
# notes/config/logging.conf – Stand Tag 08
format = text
motd.txt: |-
Willkommen bei notes im Namespace notes.
.AsConfig formt jede Datei zu einem Schlüssel mit
Block-String. motd.txt geht den Umweg über
.Files.Get und tpl, weil darin
Template-Ausdrücke stehen. Der Glob *.conf lässt
motd.txt bewusst aus, sonst stünde sie ungerendert doppelt
drin.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Wann Files einen leeren String liefert
# auf prod
mkdir -p notes/entwurf
echo 'geheim = ja' > notes/entwurf/neu.conf
printf 'alice\nbob\n' > notes/config/admins.txt
cat > notes/templates/spielwiese.yaml <<'EOF'
apiVersion: v1
kind: ConfigMap
metadata:
name: spiel
data:
admins: {{ range .Files.Lines "config/admins.txt" }}{{ . }},{{ end }}
anzahl: {{ len (.Files.Glob "config/*") | quote }}
ausTemplates: {{ .Files.Get "templates/service.yaml" | quote }}
ausEntwurf: {{ .Files.Get "entwurf/neu.conf" | quote }}
tippfehler: {{ .Files.Get "config/limit.conf" | quote }}
---
apiVersion: v1
kind: Secret
metadata:
name: spiel
data:
{{- (.Files.Glob "config/logging.conf").AsSecrets | nindent 2 }}
EOF
helm template notes ./notes -s templates/spielwiese.yaml \
| grep -v -E '^(---|#|apiVersion|kind|metadata| name)'
rm -r notes/templates/spielwiese.yaml notes/entwurf notes/config/admins.txtErwartet (gekürzt):
data:
logging.conf: IyBub3Rlcy9jb25maWcvbG9nZ2luZy5jb25mIOKAkyBTdGFuZCBUYWcgMDgKZm9ybWF0…
data:
admins: alice,bob,
anzahl: "4"
ausTemplates: ""
ausEntwurf: ""
tippfehler: ""
Drei leere Strings, keine Warnung: templates/ ist für
.Files gesperrt, entwurf/ schließt
.helmignore seit Tag 2 aus, und der Tippfehler
limit.conf fällt genauso still durch. Prüfe darum jede neue
Datei mit helm template -s. .AsSecrets kodiert
Base64 für Secret.data; Helm sortiert das Secret vor die
ConfigMap.
Fortschritt speichern? Kostenlos registrieren
Drill 3: existingSecret für den API-Key
Bisher steht lab-key-123 im Klartext in
values.yaml und damit in Git, im Release-Secret und im
Manifest. Ab jetzt verweist das Chart nur noch auf ein Secret. Gleich
mit vorbereitet: der Verweis auf ein Datenbank-Passwort für Tag 9.
# auf prod
cat > notes/values.yaml <<'EOF'
# notes/values.yaml – Stand Tag 08
# -- 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 (leer = appVersion)
tag: ""
apiKey:
# -- Name eines vorhandenen Secrets mit dem API-Key (Pflicht)
existingSecret: ""
# -- Schlüssel im Secret
key: api-key
database:
# -- Vorhandenes Secret mit dem DB-Passwort (leer = Speicher statt Postgres)
existingSecret: ""
# -- Schlüssel im Secret
passwordKey: password
# -- Host der Datenbank (Pflicht, wenn existingSecret gesetzt ist)
host: ""
port: 5432
name: notes
user: notes
# -- 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 den Service des Charts
hosts: []
# -- Ersetzt den Chart-Namen in Namen und Labels
nameOverride: ""
# -- Ersetzt den vollständigen Namen aller Objekte
fullnameOverride: ""
# -- Zeit zum sauberen Beenden (Go-Dauer wie 30s, 1m)
shutdownTimeout: 30s
EOF
cat > notes/templates/deployment.yaml <<'EOF'
{{/* notes/templates/deployment.yaml – Stand Tag 08 */}}
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:
terminationGracePeriodSeconds: {{ durationSeconds .Values.shutdownTimeout }}
containers:
- name: notes-api
image: {{ include "notes.image" . | quote }}
ports: [{name: http, containerPort: 8080}]
env:
- name: NOTES_API_KEY
valueFrom:
secretKeyRef:
name: {{ required "apiKey.existingSecret fehlt"
.Values.apiKey.existingSecret }}
key: {{ .Values.apiKey.key }}
{{- with .Values.database }}
{{- if .existingSecret }}
- name: NOTES_DB_PASSWORD
valueFrom:
secretKeyRef:
name: {{ .existingSecret }}
key: {{ .passwordKey }}
- name: NOTES_DB_URL
value: {{ printf "postgres://%s:$(NOTES_DB_PASSWORD)@%s:%v/%s?%s"
.user (required "database.host fehlt" .host) .port .name
"sslmode=disable" | quote }}
{{- end }}
{{- end }}
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
helm template notes ./notes -s templates/deployment.yaml 2>&1 | head -1
helm template notes ./notes -s templates/deployment.yaml \
--set apiKey.existingSecret=notes-api-key | sed -n '/env:/,/envFrom/p'
helm template notes ./notes -s templates/deployment.yaml \
--set apiKey.existingSecret=notes-api-key --set database.existingSecret=notes-db \
--set database.host=pg | grep -A1 'name: NOTES_DB_URL'Erwartet:
Error: execution error at (notes/templates/deployment.yaml:30:27): apiKey.existingSecret
fehlt
env:
- name: NOTES_API_KEY
valueFrom:
secretKeyRef:
name: notes-api-key
key: api-key
envFrom:
- name: NOTES_DB_URL
value: "postgres://notes:$(NOTES_DB_PASSWORD)@pg:5432/notes?sslmode=di…
$(NOTES_DB_PASSWORD) ersetzt Kubernetes beim Pod-Start,
weil die Variable weiter oben in derselben Liste steht. So bleibt das
Passwort im Secret, und das Chart baut trotzdem die URL, die notes-api
erwartet.
Fortschritt speichern? Kostenlos registrieren
Drill 4: Secret anlegen, upgraden, Lecks prüfen
# auf prod
kubectl -n notes create secret generic notes-api-key \
--from-literal=api-key=lab-key-123
cat >> values/prod.yaml <<'EOF'
apiKey:
existingSecret: notes-api-key
EOF
sed -i 's/Stand Tag 07/Stand Tag 08/' values/prod.yaml
sed -i 's/^version: .*/version: 0.7.0/; s/Tag 07/Tag 08/' notes/Chart.yaml
helm lint notes -f values/prod.yaml | tail -1
helm upgrade notes ./notes -n notes -f values/prod.yaml --wait | grep REVISION
helm get values notes -n notes | head -3
helm get manifest notes -n notes | grep -c lab-key
kubectl -n notes get cm notes-files -o jsonpath='{.data.motd\.txt}{"\n"}'Erwartet:
secret/notes-api-key created
1 chart(s) linted, 0 chart(s) failed
REVISION: 19
USER-SUPPLIED VALUES:
apiKey:
existingSecret: notes-api-key
0
Willkommen bei notes im Namespace notes.
Der Key steht weder in den Werten noch im Manifest des Releases. Wer ihn lesen will, braucht Leserechte auf das Secret – und das regelt RBAC, nicht das Chart.
Fortschritt speichern? Kostenlos registrieren
Drill 5: Was der API-Key schützt
Ein Blick auf die Schnittstelle, bevor du dich auf den Key verlässt:
# auf prod
curl -s -w ' %{http_code}\n' -H 'Host: api.notes.lab' localhost/notes \
-d '{"text":"ohne Key"}'
curl -s -w ' %{http_code}\n' -H 'Host: api.notes.lab' -H 'X-API-Key: lab-key-123' \
localhost/notes -d '{"text":"erste Notiz"}'
for i in 1 2 3 4; do
curl -s -w ' %{http_code}\n' -H 'Host: api.notes.lab' localhost/notes; doneErwartet (IDs gekürzt):
{"error":"invalid api key"} 401
{"id":"43d2d3b5-…","text":"erste Notiz"} 201
[{"id":"43d2d3b5-…","text":"erste Notiz"}] 200
[] 200
[{"id":"43d2d3b5-…","text":"erste Notiz"}] 200
[] 200
Zwei Befunde. Erstens: notes-api prüft den Key nur beim Schreiben
(POST), GET /notes ist ohne Key offen – wer
lesen schützen will, braucht davor einen Ingress mit Authentifizierung
oder eine NetworkPolicy. Zweitens: Ohne Datenbank hat jeder der zwei
Pods seinen eigenen Speicher, die Notiz erscheint nur bei jedem zweiten
Aufruf. Tag 9 gibt dem Release eine Datenbank. Direkt nach einem Upgrade
kann Traefik kurz noch auf einen beendeten Pod zeigen und
502 liefern.
Fortschritt speichern? Kostenlos registrieren
Drill 6: values.schema.json
Das Schema ersetzt die fail-Regel aus Tag 7 und fängt
zusätzlich Tippfehler in Schlüsselnamen.
# auf prod
cat > notes/values.schema.json <<'EOF'
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "notes – Stand Tag 08",
"type": "object",
"additionalProperties": false,
"required": ["image", "apiKey"],
"properties": {
"replicaCount": {"type": ["integer", "null"], "minimum": 0},
"image": {
"type": "object",
"additionalProperties": false,
"required": ["repository"],
"properties": {
"repository": {"type": "string", "minLength": 1},
"tag": {"type": "string"}
}
},
"apiKey": {
"type": "object",
"required": ["existingSecret", "key"],
"properties": {
"existingSecret": {"type": "string"},
"key": {"type": "string", "minLength": 1}
}
},
"database": {"type": "object"},
"env": {
"type": "object",
"additionalProperties": {"type": "string"},
"properties": {
"NOTES_LOG_LEVEL": {"enum": ["debug", "info", "warn", "error"]}
}
},
"team": {"type": "string"},
"resources": {"type": "object"},
"nodeSelector": {"type": "object"},
"service": {"type": "object"},
"ingress": {"type": "object"},
"nameOverride": {"type": "string"},
"fullnameOverride": {"type": "string"},
"shutdownTimeout": {"type": "string", "pattern": "^([0-9]+(ms|s|m|h))+$"}
}
}
EOF
cat > notes/templates/config.yaml <<'EOF'
{{/* notes/templates/config.yaml – Stand Tag 08 (Log-Level prüft das Schema) */}}
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 lint notes -f values/prod.yaml | tail -1
helm lint notes --set replicaCount=abc | grep ERROR
helm template notes ./notes -f values/prod.yaml --set replicas=3 \
--set env.NOTES_LOG_LEVEL=WARN --set replicaCount=-1 --set shutdownTimeout=30Erwartet:
1 chart(s) linted, 0 chart(s) failed
[ERROR] values.yaml: - at '/replicaCount': got string, want null or integer
[ERROR] templates/: values don't meet the specifications of the schema(s) in the
following chart(s):
Error: values don't meet the specifications of the schema(s) in the following chart(s):
notes:
- at '/env/NOTES_LOG_LEVEL': value must be one of 'debug', 'info', 'warn', 'error'
- at '/shutdownTimeout': got number, want string
- at '/replicaCount': minimum: got -1, want 0
- at '': additional properties 'replicas' not allowed
Vier Fehler in einem Lauf – required und
fail hätten beim ersten aufgehört. Ohne Schema wäre
replicas=3 still verpufft.
"type": ["integer", "null"] erlaubt das null
aus Tag 3, das den Standard löscht.
Fortschritt speichern? Kostenlos registrieren
Drill 7: Schema bei upgrade und seine Grenzen
# auf prod
helm upgrade notes ./notes -n notes -f values/prod.yaml --set env.NOTES_LOG_LEVEL=laut
helm history notes -n notes --max 1 -o json | jq -r '.[0].revision'
helm template notes ./notes -f values/prod.yaml --set-string replicaCount=2 2>&1 \
| grep 'at 'Erwartet:
Error: UPGRADE FAILED: values don't meet the specifications of the schema(s) in the
following chart(s):
notes:
- at '/env/NOTES_LOG_LEVEL': value must be one of 'debug', 'info', 'warn', 'error'
19
- at '/replicaCount': got string, want null or integer
Das Upgrade scheitert vor dem Rendern, Revision 19 bleibt.
--set-string ist hier die Falle: Aus 2 wird
"2", und das Schema lehnt ab. Helm 4 versteht auch neuere
Drafts und lädt entfernte $ref beim Rendern nach – im
abgeschotteten CI ein Problem:
# auf prod
cd ~/helm/tag08 && mkdir -p s/templates
printf 'apiVersion: v2\nname: s\nversion: 0.1.0\n' > s/Chart.yaml
cat > s/values.schema.json <<'EOF'
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$defs": {"port": {"type": "integer", "minimum": 1, "maximum": 65535}},
"type": "object",
"properties": {"port": {"$ref": "#/$defs/port"}}
}
EOF
helm template x ./s --set port=70000 2>&1 | grep 'at '
cat > s/values.schema.json <<'EOF'
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {"port": {"$ref": "https://example.com/port.json"}}
}
EOF
helm template x ./s --set port=1 2>&1 | tail -1Erwartet:
- at '/port': maximum: got 70,000, want 65,535
failing loading "https://example.com/port.json": HTTP request to
https://example.com/port.json returned status 404 (Not Found)
Schemas darum in sich geschlossen halten: Definitionen unter
$defs statt fremder URLs.
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Zeig nur die Schema-Fehlerzeile für
--set team=1. Zeitziel: 20 s - Prüfe, ob das Manifest des Releases den API-Key enthält. Zeitziel: 15 s
- Liste die Schlüssel der ConfigMap
notes-files. Zeitziel: 20 s - Lies den API-Key aus dem Secret im Klartext. Zeitziel: 20 s
Lösung
# auf prod
cd ~/helm/charts
helm template notes ./notes -f values/prod.yaml --set team=1 2>&1 | grep 'at '
helm get manifest notes -n notes | grep -c lab-key
kubectl -n notes get cm notes-files -o json | jq -r '.data | keys[]'
kubectl -n notes get secret notes-api-key -o jsonpath='{.data.api-key}' \
| base64 -d; echoErwartet:
- at '/team': got number, want string
0
limits.conf
logging.conf
motd.txt
lab-key-123
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
# auf prod
helm list -n notesErwartet: Revision 19, notes-0.7.0,
deployed.
# auf prod
helm lint ~/helm/charts/notes --set replicas=3 | tail -1Erwartet:
Error: 1 chart(s) linted, 1 chart(s) failed
# auf prod
kubectl -n notes get deploy notes \
-o jsonpath='{.spec.template.spec.containers[0].env[0].valueFrom}{"\n"}'Erwartet:
{"secretKeyRef":{"key":"api-key","name":"notes-api-key"}}
Challenge
Ersetze in einer Kopie das lockere
"ingress": {"type": "object"} durch eine echte Regel:
enabled ist ein Boolean, hosts eine Liste von
Strings, und wenn enabled wahr ist, muss hosts
mindestens einen Eintrag haben.
Hinweis: draft-07 kennt
if/then auf Objektebene; const
prüft einen festen Wert.
Lösung
# auf prod
cd ~/helm/tag08 && rm -rf notes && cp -r ~/helm/charts/notes .
jq '.properties.ingress = {
"type": "object",
"properties": {
"enabled": {"type": "boolean"},
"className": {"type": "string"},
"hosts": {"type": "array", "items": {"type": "string"}}
},
"if": {"properties": {"enabled": {"const": true}}},
"then": {"required": ["hosts"], "properties": {"hosts": {"minItems": 1}}}
}' notes/values.schema.json > s.json && mv s.json notes/values.schema.json
helm template notes ./notes --set apiKey.existingSecret=x --set ingress.enabled=true \
2>&1 | grep 'at '
helm template notes ./notes --set apiKey.existingSecret=x --set ingress.enabled=yes \
2>&1 | grep 'at '
helm template notes ./notes -f ~/helm/charts/values/prod.yaml \
-s templates/ingress.yaml | grep -c host:Erwartet:
- at '/ingress/hosts': minItems: got 0, want 1
- at '/ingress/enabled': got string, want boolean
2
yes ist bei --set ein String, kein Boolean
– das Schema merkt es, das Template mit
if .Values.ingress.enabled hätte den Ingress angelegt.
Fortschritt speichern? Kostenlos registrieren
Aufräumen
# auf prod
cd ~/helm/charts
git add -A
git commit -qm "Tag 08: Dateien, existingSecret, values.schema.json, notes 0.7.0"Interview-Notiz
- Wie bringst du eine große Konfigurationsdatei in ein Chart?
Als Datei neben
templates/, eingelesen mit.Files.Getoder(.Files.Glob "…").AsConfig; braucht sie Werte, zusätzlichtpl. Dateien intemplates/oder in.helmignoresind unsichtbar. - Wie gehst du mit Secrets im Chart um? Das Chart verweist
per
existingSecretauf ein Secret, das ein anderer Weg erzeugt (External Secrets, SOPS, Sealed Secrets). Kein Klartext in Werten – die landen im Release-Secret. - Wozu
values.schema.json? Es prüft Typen, Pflichtfelder, Wertebereiche und Tippfehler vor dem Rendern, meldet alles auf einmal und dokumentiert die Schnittstelle.
Enterprise-Notiz
- Das Schema ist Teil der Chart-API: ein neues Pflichtfeld oder
additionalProperties: falsenachträglich ist ein Breaking Change (Major-Version). - Editoren mit YAML-Language-Server prüfen
values.yamlgegen das Schema und vervollständigen Schlüssel (Kommentar# yaml-language-server: $schema=…). helm-docs dagegen liest nurvalues.yamlmit seinen# ---Kommentaren, nicht das Schema – beides pflegst du getrennt. - Abgeschottete CI-Umgebungen: keine entfernten
$refim Schema, sonst scheitert jedes Rendern ohne Internet. - Ein offenes
GETwie bei notes-api ist ein Befund für die Sicherheitsprüfung, nicht für das Chart – das Chart kann aber eine NetworkPolicy oder Ingress-Auth anbieten.