Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 17: Lint, kubeconform und helm-unittest

Ziel: Ein Chart ohne Cluster gegen Tippfehler, Schema-Verstöße, unsichere Einstellungen und veraltete APIs prüfen und sein Verhalten mit Unit-Tests festhalten. · Dauer: ca. 75 min · Voraussetzung: Tag 16

Briefing

  • helm lint prüft das Chart (Struktur, Werte-Schema, Template-Syntax), nicht das Kubernetes-Schema der gerenderten Objekte.
  • helm template | kubeconform -strict prüft jedes Objekt gegen das OpenAPI-Schema – pro Umgebung, also pro Werte-Datei.
  • kubectl apply --dry-run=server fragt einen echten API-Server (Staging), trivy config sucht unsichere Einstellungen, pluto veraltete APIs.
  • helm-unittest rendert lokal und prüft Pfade im Ergebnis: jede Bedingung im Template ein Test.
 helm lint ─▶ helm unittest ─▶ helm template | kubeconform ─▶ trivy / pluto
     (Chart)       (Verhalten)        (Schema je Umgebung)       (Sicherheit, APIs)
                                   └─▶ kubectl apply --dry-run=server (Staging)

Drill 1: Werkzeuge

trivy benennt seine Archive nicht nach Debian-Architektur – ein case übersetzt:

# auf prod
mkdir -p ~/helm/tag17/bin && cd ~/helm/tag17/bin
ARCH=$(dpkg --print-architecture)
case $ARCH in amd64) TA=64bit ;; arm64) TA=ARM64 ;; esac
K=https://github.com/yannh/kubeconform/releases/download/v0.8.0
P=https://github.com/FairwindsOps/pluto/releases/download/v5.24.5
T=https://github.com/aquasecurity/trivy/releases/download/v0.76.2
curl -fsSLO $K/kubeconform-linux-$ARCH.tar.gz && curl -fsSLO $K/CHECKSUMS
curl -fsSLO $P/pluto_5.24.5_linux_$ARCH.tar.gz && curl -fsSLO $P/checksums.txt
curl -fsSLO $T/trivy_0.76.2_Linux-$TA.tar.gz
curl -fsSLO $T/trivy_0.76.2_checksums.txt
grep " kubeconform-linux-$ARCH.tar.gz$" CHECKSUMS | sha256sum -c
grep " pluto_5.24.5_linux_$ARCH.tar.gz$" checksums.txt | sha256sum -c
grep " trivy_0.76.2_Linux-$TA.tar.gz$" trivy_0.76.2_checksums.txt | sha256sum -c
tar -xzf kubeconform-linux-$ARCH.tar.gz kubeconform
tar -xzf pluto_5.24.5_linux_$ARCH.tar.gz pluto
tar -xzf trivy_0.76.2_Linux-$TA.tar.gz trivy
sudo install -m 755 kubeconform pluto trivy /usr/local/bin/
kubeconform -v; pluto version | cut -d' ' -f1; trivy --version | head -1

Erwartet:

kubeconform-linux-amd64.tar.gz: OK
pluto_5.24.5_linux_amd64.tar.gz: OK
trivy_0.76.2_Linux-64bit.tar.gz: OK
v0.8.0
Version:5.24.5
Version: 0.76.2

Fortschritt speichern? Kostenlos registrieren

Drill 2: Was helm lint sieht – und was nicht

# auf prod
cd ~/helm/charts
helm lint notes --strict -f values/prod.yaml
helm lint notes --strict --with-subcharts -f values/prod.yaml | grep -E 'Linting|linted'

Erwartet:

==> Linting notes
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, 0 chart(s) failed
==> Linting notes
==> Linting notes/charts/plattform-0.1.0.tgz
==> Linting notes/charts/postgres-0.1.0.tgz
3 chart(s) linted, 0 chart(s) failed

--strict macht Warnungen zu Fehlern, --with-subcharts prüft die Abhängigkeiten mit. Jetzt ein Tippfehler im Template – in einer Kopie:

# auf prod
cd ~/helm/tag17 && cp -r ~/helm/charts/notes .
sed -i 's/^  replicas:/  replica:/' notes/templates/deployment.yaml
helm lint notes --strict -f ~/helm/charts/values/prod.yaml | tail -1
helm template notes ./notes -f ~/helm/charts/values/prod.yaml \
  -s templates/deployment.yaml | grep -A1 '^spec:'

Erwartet:

1 chart(s) linted, 0 chart(s) failed
spec:
  replica: 2

replica ist gültiges YAML, und Helm kennt das Kubernetes-Schema beim Linten nicht. Ein Tippfehler in den Werten (replicaCont: 3) fiele dagegen auf – das Schema aus Tag 8 verbietet unbekannte Schlüssel.

Fortschritt speichern? Kostenlos registrieren

Drill 3: kubeconform für jede Umgebung

# auf prod
cd ~/helm/charts
for env in dev staging prod; do
  echo "== $env"; helm template notes ./notes -f values/$env.yaml 2>/dev/null \
    | kubeconform -strict -summary
done

Erwartet:

== dev
Summary: 0 resource found parsing stdin - Valid: 0, Invalid: 0, Errors: 0, Skipped: 0
== staging
Summary: 0 resource found parsing stdin - Valid: 0, Invalid: 0, Errors: 0, Skipped: 0
== prod
Summary: 10 resources found parsing stdin - Valid: 10, Invalid: 0, Errors: 0, Skipped: 0

Null Ressourcen und keine Fehler – eine grüne Pipeline, die nichts geprüft hat. Der Grund:

# auf prod
set -o pipefail
helm template notes ./notes -f values/dev.yaml 2>&1 >/dev/null | head -1 | fold -w 88
helm template notes ./notes -f values/dev.yaml 2>/dev/null \
  | kubeconform -strict -summary >/dev/null 2>&1; echo "Exit: $?"

Erwartet:

Error: execution error at (notes/templates/deployment.yaml:35:27): apiKey.existingSecret
 fehlt
Exit: 1

Seit Tag 8 ist apiKey.existingSecret Pflicht, dev.yaml und staging.yaml sind seit Tag 3 nicht mitgewachsen. Ohne pipefail zählt in einer Pipe nur der Exit-Code des letzten Befehls. Beide Dateien reparieren, dann noch einmal – und die Kopie mit dem Tippfehler:

# auf prod
for env in dev staging; do
  yq -i '.apiKey.existingSecret = "notes-api-key"' values/$env.yaml
  sed -i "1s/Stand Tag 03/Stand Tag 17/" values/$env.yaml
done
cat values/dev.yaml
for env in dev staging prod; do
  echo "== $env"; helm template notes ./notes -f values/$env.yaml \
    | kubeconform -strict -summary
done
helm template notes ~/helm/tag17/notes -f values/prod.yaml \
  | kubeconform -strict -summary \
  | grep -oE "Deployment notes is invalid|at '/spec'.*|Summary.*"

Erwartet:

# values/dev.yaml – Stand Tag 17
replicaCount: 1
env:
  NOTES_LOG_LEVEL: debug
  NOTES_FEATURE_TAGS: "on"
apiKey:
  existingSecret: notes-api-key
== dev
Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0
== staging
Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0
== prod
Summary: 10 resources found parsing stdin - Valid: 10, Invalid: 0, Errors: 0, Skipped: 0
Deployment notes is invalid
at '/spec': additional properties 'replica' not allowed
Summary: 10 resources found parsing stdin - Valid: 9, Invalid: 1, Errors: 0, Skipped: 0

-strict verbietet zusätzliche Felder – ohne das Flag wäre replica durchgerutscht. kubeconform lädt die Schemas aus dem Netz (Standard: Kubernetes master); mit -kubernetes-version prüfst du gegen die Version des Zielclusters. CRDs (z. B. NoteBackup) brauchen eigene Schemas oder -ignore-missing-schemas.

Fortschritt speichern? Kostenlos registrieren

Drill 4: Gegen einen echten API-Server

kubeconform kennt nur Schemas. Ein Server-Probelauf gegen Staging prüft zusätzlich Admission, Defaults und Quotas. tag17 spielt hier Staging:

# auf prod
kubectl create namespace tag17
helm template notes ~/helm/tag17/notes -f values/staging.yaml -n tag17 \
  | kubectl apply --dry-run=server -n tag17 -f - 2>&1 | grep -v created | fold -w 88
helm template notes ~/helm/tag17/notes -f values/staging.yaml -n tag17 \
  | kubectl apply --dry-run=server --server-side -n tag17 -f - 2>&1 \
  | grep -v applied | fold -w 88
helm template notes ./notes -f values/staging.yaml -n tag17 --skip-tests --no-hooks \
  | kubectl apply --dry-run=server --server-side -n tag17 -f -
kubectl -n tag17 get secret notes-api-key 2>&1

Erwartet:

namespace/tag17 created
Error from server (BadRequest): error when creating "STDIN": Deployment in version "v1"
cannot be handled as a Deployment: strict decoding error: unknown field "spec.replica"
Error from server: failed to create typed patch object (tag17/notes; apps/v1, Kind=Deplo
yment): .spec.replica: field not declared in schema
configmap/notes-config serverside-applied (server dry run)
configmap/notes-info serverside-applied (server dry run)
configmap/notes-files serverside-applied (server dry run)
service/notes serverside-applied (server dry run)
deployment.apps/notes serverside-applied (server dry run)
Error from server (NotFound): secrets "notes-api-key" not found

Beide Wege finden den Tippfehler. helm template rendert Test-Pods und Hooks mit; --skip-tests --no-hooks lässt sie weg, sonst „legt“ der Probelauf auch sie an. Was der Probelauf nicht prüft: Verweise. Das Secret notes-api-key fehlt in Staging, der Pod würde mit CreateContainerConfigError hängen. Für Typfehler im Chart reicht helm install --dry-run=server übrigens nicht (Tag 4) – erst kubectl apply validiert streng.

Fortschritt speichern? Kostenlos registrieren

Drill 5: Unsichere Einstellungen und alte APIs

# auf prod
cd ~/helm/charts
helm template notes ./notes -f values/prod.yaml -n notes --skip-tests \
  > ~/helm/tag17/prod.yaml
cd ~/helm/tag17
trivy config --quiet --format json prod.yaml | jq -r '.Results[].Misconfigurations[]?
  | .Severity' | sort | uniq -c
trivy config --quiet --format json --severity HIGH,CRITICAL prod.yaml \
  | jq -r '.Results[].Misconfigurations[]? | "\(.ID) \(.Message)"' | cut -c1-88
trivy config --quiet --severity HIGH,CRITICAL --exit-code 1 prod.yaml >/dev/null
echo "Exit: $?"

Erwartet:

      3 HIGH
     19 LOW
      6 MEDIUM
KSV-0014 Container 'postgres' of StatefulSet 'notes-postgres' should set 'securityContex
KSV-0118 container notes-postgres in default namespace is using the default security con
KSV-0118 statefulset notes-postgres in default namespace is using the default security c
Exit: 1

Alle HIGH-Befunde treffen das Subchart postgres – derselbe Befund wie die PSA-Probe in Tag 10. notes-api mit den restricted-Kontexten aus plattform ist sauber. --exit-code 1 mit Schweregrad-Filter macht daraus ein Tor; „in default namespace“ kommt daher, dass helm template kein metadata.namespace schreibt. Jetzt veraltete APIs:

# auf prod
pluto detect prod.yaml; echo "Exit: $?"
cat > alt.yaml <<'EOF'
apiVersion: policy/v1beta1
kind: PodDisruptionBudget
metadata:
  name: alt
spec:
  maxUnavailable: 1
  selector:
    matchLabels: {app: alt}
EOF
pluto detect alt.yaml; echo "Exit: $?"
pluto detect alt.yaml --target-versions k8s=v1.20.0; echo "Exit: $?"
pluto detect-helm; echo "Exit: $?"
cd ~/helm/charts
helm lint notes -f values/prod.yaml --kube-version 1.32.0 | tail -1
helm template notes ./notes -f values/prod.yaml --kube-version 1.32.0 2>&1 \
  | head -1 | fold -w 88

Erwartet (gekürzt):

There were no resources found with known deprecated apiVersions.
Exit: 0
NAME   KIND                  VERSION          REPLACEMENT   REMOVED   DEPRECATED   ...
alt    PodDisruptionBudget   policy/v1beta1   policy/v1     true      true         ...
Exit: 3
No output to display
Exit: 0
There were no resources found with known deprecated apiVersions.
Exit: 0
1 chart(s) linted, 0 chart(s) failed
Error: chart requires kubeVersion: >=1.33.0-0 which is incompatible with Kubernetes v1.3
2.0

pluto prüft gegen eine Zielversion: Für 1.20 war policy/v1beta1 noch nicht veraltet. Exit 3 heißt „entfernt“, 2 „veraltet“. detect-helm liest die gespeicherten Manifeste aller Releases – genau dort steckt das Problem, das Tag 19 in Drill 8 repariert. helm lint ignoriert kubeVersion aus Chart.yaml auch mit --kube-version, helm template nicht.

Fortschritt speichern? Kostenlos registrieren

Drill 6: helm-unittest und die erste Suite

Unter Helm 4 als signiertes Plugin-Archiv (die Anleitung des Projekts nennt für die Git-Installation --verify=false – das braucht es mit dem Archiv nicht):

# auf prod
mkdir -p ~/helm/tag17/unittest && cd ~/helm/tag17/unittest
U=https://github.com/helm-unittest/helm-unittest/releases/download/v1.2.1
curl -fsSLO $U/unittest-1.2.1.tgz && curl -fsSLO $U/unittest-1.2.1.tgz.prov
curl -fsSL -o public-key.asc \
  https://raw.githubusercontent.com/helm-unittest/helm-unittest/v1.2.1/public-key.asc
gpg --show-keys public-key.asc | sed -n 2,3p
gpg --no-default-keyring --keyring ./unittest.kbx --import public-key.asc 2>&1 | tail -1
helm plugin install unittest-1.2.1.tgz --keyring ./unittest.kbx | tail -1
helm plugin list | awk '$1=="unittest" {print $1, $2, $5}'

Erwartet:

      853008CD0B0A5A2DA04FF8A5616AD47F65B54AC7
uid                      helm-unittest Plugin <[email protected]>
gpg:               imported: 1
Installed plugin: unittest
unittest 1.2.1 signed

Suites liegen in notes/tests/*_test.yaml. Jede Bedingung im Deployment-Template bekommt einen Test:

# auf prod
cd ~/helm/charts && mkdir -p notes/tests
cat > notes/tests/deployment_test.yaml <<'EOF'
# notes/tests/deployment_test.yaml – Stand Tag 17
suite: Deployment
templates:
  - templates/deployment.yaml
  - templates/config.yaml
release:
  name: notes
set:
  apiKey.existingSecret: notes-api-key
tests:
  - it: erzeugt genau ein Deployment
    template: templates/deployment.yaml
    asserts:
      - hasDocuments:
          count: 1
      - isKind:
          of: Deployment
  - it: nimmt appVersion als Image-Tag
    template: templates/deployment.yaml
    asserts:
      - equal:
          path: spec.template.spec.containers[0].image
          value: ghcr.io/thomaszachmann/notes-api:0.7.1
  - it: nimmt einen gesetzten Tag
    template: templates/deployment.yaml
    set:
      image.tag: 0.8.0-rc.1
    asserts:
      - matchRegex:
          path: spec.template.spec.containers[0].image
          pattern: :0\.8\.0-rc\.1$
  - it: erlaubt null Replikas
    template: templates/deployment.yaml
    set:
      replicaCount: 0
    asserts:
      - equal:
          path: spec.replicas
          value: 0
  - it: liest den API-Key aus dem vorhandenen Secret
    template: templates/deployment.yaml
    asserts:
      - contains:
          path: spec.template.spec.containers[0].env
          content:
            name: NOTES_API_KEY
            valueFrom:
              secretKeyRef:
                name: notes-api-key
                key: api-key
  - it: setzt ohne Werte keinen nodeSelector
    template: templates/deployment.yaml
    asserts:
      - notExists:
          path: spec.template.spec.nodeSelector
  - it: verlangt apiKey.existingSecret
    template: templates/deployment.yaml
    set:
      apiKey.existingSecret: ""
    asserts:
      - failedTemplate:
          errorMessage: apiKey.existingSecret fehlt
EOF
helm unittest notes

Erwartet (gekürzt):

### Chart [ notes ] notes

 PASS  Deployment       notes/tests/deployment_test.yaml

Charts:      1 passed, 1 total
Test Suites: 1 passed, 1 total
Tests:       7 passed, 7 total
Snapshot:    0 passed, 0 total

Warum steht config.yaml in der Liste? Das Deployment liest die Datei per include für die Prüfsumme (Tag 7). helm-unittest rendert nur die genannten Templates – fehlt sie, scheitert jeder Test:

# auf prod
cp notes/tests/deployment_test.yaml ~/helm/tag17/ohne-config.yaml
yq -i 'del(.templates[1])' ~/helm/tag17/ohne-config.yaml
helm unittest notes -f ../../tag17/ohne-config.yaml 2>&1 \
  | grep -m1 -A1 'error calling include'
helm unittest notes -f ../../tag17/ohne-config.yaml 2>&1 | grep '^Tests:'

Erwartet:

    error calling include:
template: no template "notes/templates/config.yaml" associated with template "gotpl"
Tests:       7 failed, 6 errored, 0 passed, 7 total

Mit zwei Templates in templates: braucht jeder Test template:, sonst gelten die Prüfungen für beide Dateien. -f ist relativ zum Chart-Ordner.

Fortschritt speichern? Kostenlos registrieren

Drill 7: Ingress, Schema und der Tippfehler

# auf prod
cat > notes/tests/ingress_test.yaml <<'EOF'
# notes/tests/ingress_test.yaml – Stand Tag 17
suite: Ingress
templates:
  - templates/ingress.yaml
release:
  name: notes
tests:
  - it: fehlt ohne enabled
    asserts:
      - hasDocuments:
          count: 0
  - it: fehlt ohne Hosts
    set:
      ingress.enabled: true
    asserts:
      - hasDocuments:
          count: 0
  - it: rendert Hosts mit tpl
    set:
      ingress.enabled: true
      ingress.hosts: ["{{ .Release.Name }}.lab", "api.{{ .Release.Name }}.lab"]
    asserts:
      - equal:
          path: spec.rules[1].host
          value: api.notes.lab
      - equal:
          path: metadata.annotations["traefik.ingress.kubernetes.io/router.entrypoints"]
          value: web
  - it: setzt die Traefik-Annotation nur für traefik
    set:
      ingress.enabled: true
      ingress.hosts: [notes.lab]
      ingress.className: nginx
    asserts:
      - notExists:
          path: metadata.annotations
EOF
cat > notes/tests/schema_test.yaml <<'EOF'
# notes/tests/schema_test.yaml – Stand Tag 17
suite: Schema
templates:
  - templates/deployment.yaml
set:
  apiKey.existingSecret: notes-api-key
tests:
  - it: lehnt Text als Replikazahl ab
    set:
      replicaCount: abc
    asserts:
      - failedTemplate:
          errorPattern: "got string, want (integer|null)"
  - it: lehnt unbekannte Schlüssel ab
    set:
      replica: 3
    asserts:
      - failedTemplate:
          errorPattern: "additional properties 'replica' not allowed"
EOF
helm unittest notes | grep -E 'PASS|FAIL|^Tests:'
cp -r notes/tests ~/helm/tag17/notes/
helm unittest ~/helm/tag17/notes 2>&1 | grep -E 'FAIL|^\s+- |^Tests:' | head -4

Erwartet:

 PASS  Deployment       notes/tests/deployment_test.yaml
 PASS  Ingress  notes/tests/ingress_test.yaml
 PASS  Schema   notes/tests/schema_test.yaml
Tests:       13 passed, 13 total
 FAIL  Deployment       ../tag17/notes/tests/deployment_test.yaml
        - erlaubt null Replikas
                - asserts[0] `equal` fail
Tests:       1 failed, 12 passed, 13 total

Das Schema prüft helm-unittest wie helm install – failedTemplate fängt auch Schema-Fehler. Und der Tippfehler aus Drill 2 fällt dem Test „erlaubt null Replikas“ auf: Er sucht spec.replicas und findet es nicht.

Fortschritt speichern? Kostenlos registrieren

Drill 8: Snapshots und die Tests im Paket

matchSnapshot speichert das ganze Rendering und vergleicht künftig dagegen – in der Kopie:

# auf prod
cd ~/helm/tag17
sed -i 's/^  replica:/  replicas:/' notes/templates/deployment.yaml
cat > notes/tests/snapshot_test.yaml <<'EOF'
# notes/tests/snapshot_test.yaml – Stand Tag 17
suite: Snapshot
templates:
  - templates/deployment.yaml
  - templates/config.yaml
set:
  apiKey.existingSecret: notes-api-key
tests:
  - it: bleibt wie gespeichert
    template: templates/deployment.yaml
    asserts:
      - matchSnapshot: {}
EOF
helm unittest notes | grep -E '^(Tests|Snapshot):'
ls notes/tests/__snapshot__
sed -i 's/^version: .*/version: 0.12.1/' notes/Chart.yaml
helm unittest notes 2>&1 | grep -E 'FAIL|^\s+[-+] ' | cut -c1-70
helm unittest notes -u | grep -E '^(Tests|Snapshot):'

Erwartet:

Tests:       14 passed, 14 total
Snapshot:    1 passed, 1 total
snapshot_test.yaml.snap
 FAIL  Snapshot notes/tests/snapshot_test.yaml
        -    helm.sh/chart: notes-0.12.0
        +    helm.sh/chart: notes-0.12.1
        -        checksum/config: a186697cb32d9f9aaa5ec92fcf56373635ad021e
        +        checksum/config: b065edf6dee5e70d94d5b95a3c9cb8f762285970
        -        helm.sh/chart: notes-0.12.0
        +        helm.sh/chart: notes-0.12.1
Tests:       14 passed, 14 total
Snapshot:    1 passed, 1 total

Die Falle: Jede neue Chart-Version ändert Labels und Prüfsumme, der Snapshot schlägt an, und nach dem dritten Mal ruft jeder reflexhaft -u auf – dann prüft der Test nichts mehr. Snapshots nur für kleine, stabile Teile; Verhalten mit equal und contains. Im echten Chart gibt es keinen Snapshot.

Die Suites sollen nicht ins Paket. Erster Versuch:

# auf prod
cd ~/helm/charts
sed -i '1s/Stand Tag 02/Stand Tag 17/' notes/.helmignore
printf 'tests/\n' >> notes/.helmignore
helm template notes ./notes -f values/prod.yaml | grep -c '^kind: Pod'
sed -i 's#^tests/$#/tests/#' notes/.helmignore
helm template notes ./notes -f values/prod.yaml | grep -c '^kind: Pod'
helm package notes -d /tmp >/dev/null && tar -tzf /tmp/notes-0.12.0.tgz | grep tests/
rm /tmp/notes-0.12.0.tgz
git add notes/tests notes/.helmignore values/dev.yaml values/staging.yaml
git commit -qm "Tag 17: Unit-Tests für notes, dev/staging mit existingSecret"
git log --oneline -1

Erwartet:

0
1
notes/templates/tests/api-test.yaml
45ef9c8 Tag 17: Unit-Tests für notes, dev/staging mit existingSecret

tests/ trifft jeden Ordner dieses Namens – auch templates/tests/, der Chart-Test aus Tag 11 war plötzlich weg. /tests/ meint nur den Ordner im Chart-Wurzelverzeichnis. Die Chart-Version bleibt bewusst 0.12.0; Tag 18 zeigt, wer das bemerkt.

Fortschritt speichern? Kostenlos registrieren

Übung: Speed-Drills

  1. Wie viele Tests hat die Suite Ingress? Zeitziel: 15 s
  2. Prüfe das Staging-Rendering gegen das Schema von Kubernetes 1.37.0. Zeitziel: 30 s
  3. Wie viele HIGH-/CRITICAL-Befunde hat prod.yaml? Als Zahl. Zeitziel: 30 s
  4. Enthält das gespeicherte Manifest von notes veraltete APIs? Zeitziel: 20 s

Lösung

# auf prod
helm unittest notes -f tests/ingress_test.yaml | grep '^Tests:'
helm template notes ./notes -f values/staging.yaml \
  | kubeconform -strict -summary -kubernetes-version 1.37.0 2>&1 | tail -1
trivy config --quiet --severity HIGH,CRITICAL --format json ~/helm/tag17/prod.yaml \
  | jq '[.Results[].Misconfigurations[]?] | length'
helm get manifest notes -n notes | pluto detect - ; echo "Exit: $?"

Erwartet:

Tests:       4 passed, 4 total
Summary: 6 resources found parsing stdin - Valid: 6, Invalid: 0, Errors: 0, Skipped: 0
3
There were no resources found with known deprecated apiVersions.
Exit: 0

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

# auf prod
cd ~/helm/charts
helm unittest notes | grep '^Tests:'

Erwartet: Tests: 13 passed, 13 total (nach der Challenge: 15).

# auf prod
helm template notes ./notes -f values/dev.yaml | kubeconform -strict -summary

Erwartet: Summary: 6 resources found … Valid: 6, Invalid: 0 …

# auf prod
helm test notes -n notes | grep Phase

Erwartet: Phase: Succeeded – der Chart-Test ist noch da.

Challenge

Laut Kommentar in values.yaml gilt replicaCount: null als „Standard 2“, und ein nodeSelector wird unverändert durchgereicht. Halte beides in Tests fest und committe.

Hinweis: set: in helm-unittest versteht null und Maps; equal vergleicht auch ganze Objekte.

Lösung

# auf prod
cat >> notes/tests/deployment_test.yaml <<'EOF'
  - it: nimmt bei null den Standard 2
    template: templates/deployment.yaml
    set:
      replicaCount: null
    asserts:
      - equal:
          path: spec.replicas
          value: 2
  - it: reicht den nodeSelector durch
    template: templates/deployment.yaml
    set:
      nodeSelector:
        kubernetes.io/arch: arm64
    asserts:
      - equal:
          path: spec.template.spec.nodeSelector
          value:
            kubernetes.io/arch: arm64
EOF
helm unittest notes | grep -E 'PASS|FAIL|^Tests:'
git add notes/tests
git commit -qm "Tag 17 Challenge: Tests für replicaCount null und nodeSelector"
git log --oneline -1

Erwartet:

 PASS  Deployment       notes/tests/deployment_test.yaml
 PASS  Ingress  notes/tests/ingress_test.yaml
 PASS  Schema   notes/tests/schema_test.yaml
Tests:       15 passed, 15 total
a469b3a Tag 17 Challenge: Tests für replicaCount null und nodeSelector

null löscht den Schlüssel (Tag 3), hasKey ist dann falsch, die ternary aus Tag 5 nimmt 2. Ein Test, der ein dokumentiertes Verhalten festhält, ist die beste Doku.

Fortschritt speichern? Kostenlos registrieren

Aufräumen

# auf prod
kubectl delete namespace tag17

Erwartet: namespace "tag17" deleted

Interview-Notiz

  • Was prüft helm lint, was nicht? Chart-Struktur, Werte gegen values.schema.json, Template-Syntax. Nicht das Kubernetes-Schema der Objekte – dafür kubeconform -strict oder ein Server-Probelauf.
  • Wie testest du ein Chart ohne Cluster? helm-unittest mit einem Test pro Bedingung (equal, contains, notExists, failedTemplate), dazu helm template | kubeconform für jede Werte-Datei, trivy config und pluto.
  • Was ist an Snapshot-Tests problematisch? Sie brechen bei jeder Versions- oder Label-Änderung und werden dann blind aktualisiert.

Enterprise-Notiz

  • set -o pipefail in jedem CI-Skript; eine Prüfung, die „0 resources found“ meldet, muss rot sein.
  • kubeconform-Schemas und trivy-Regeln spiegeln (Air-Gap) und auf die Version der Zielcluster pinnen; CRD-Schemas aus den eigenen Operatoren erzeugen.
  • trivy-Befunde einmal sauber bewerten und Ausnahmen begründet in .trivyignore pflegen – sonst ignoriert das Team bald alle.
  • pluto detect-helm regelmäßig gegen alle Cluster laufen lassen, vor jedem Kubernetes-Upgrade mit --target-versions der neuen Version.
  • Unit-Tests gehören in die Review-Regeln: neue Bedingung im Template ohne Test = kein Merge.