Zum Inhalt springen
Trainingslager IT-Trainingslager

Tag 4: Postgres, Sync-Waves und Hooks

Ziel: notes-api speichert in Postgres. Argo CD legt erst die Datenbank an, dann migriert ein Job das Schema, dann startet notes-api, und am Ende prüft ein Smoke-Test. · Dauer: ca. 60 min · Voraussetzung: Tag 3

Briefing

  • Ohne Vorgaben wendet Argo CD alle Objekte einer Application in einem Schwung an, nur grob nach Art sortiert (Namespaces und Secrets vor Deployments).
  • Sync-Waves legen eine Reihenfolge fest. Die Annotation argocd.argoproj.io/sync-wave: "-1" kommt vor Welle 0, die vor 1. Argo CD wartet, bis eine Welle Healthy ist, bevor es die nächste anfasst.
  • Hooks sind Objekte, meist Jobs, die nur bei einem Sync laufen: PreSync vor allen Wellen, Sync mitten in den Wellen, PostSync danach, SyncFail bei einem Fehler.
  • Die hook-delete-policy bestimmt, wann Argo CD einen Hook-Job wieder löscht.
 PreSync ─► Welle -1 ─► Welle 0 ─► Welle 1 ─► PostSync
            Postgres    Migration   notes-api   Smoke-Test
            (Secret,    (Sync-Hook)
             PVC, DB)

Drill 1: Postgres in Welle -1

Vier Dateien kommen nach apps/notes, alle mit Welle -1:

cd ~/argo-lab/argocd-fleet/apps/notes
cat > db-secret.yaml <<'EOF'
apiVersion: v1
kind: Secret
metadata:
  name: notes-db
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
stringData:
  password: lab-db-pw-123
EOF
cat > db-pvc.yaml <<'EOF'
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: notes-db
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
EOF
cat > db-service.yaml <<'EOF'
apiVersion: v1
kind: Service
metadata:
  name: notes-db
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
spec:
  selector:
    app: notes-db
  ports:
    - port: 5432
EOF
cat > db-deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes-db
  annotations:
    argocd.argoproj.io/sync-wave: "-1"
spec:
  replicas: 1
  strategy:
    type: Recreate
  selector:
    matchLabels:
      app: notes-db
  template:
    metadata:
      labels:
        app: notes-db
    spec:
      containers:
        - name: postgres
          image: postgres:18.6-alpine
          env:
            - name: POSTGRES_USER
              value: notes
            - name: POSTGRES_DB
              value: notes
            - name: POSTGRES_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: notes-db
                  key: password
            - name: PGDATA
              value: /var/lib/postgresql/data/pgdata
          ports:
            - containerPort: 5432
          readinessProbe:
            exec:
              command: ["pg_isready", "-U", "notes", "-d", "notes"]
          volumeMounts:
            - name: data
              mountPath: /var/lib/postgresql/data
      volumes:
        - name: data
          persistentVolumeClaim:
            claimName: notes-db
EOF
  • strategy: Recreate: Zwei Postgres-Pods dürfen nie gleichzeitig auf dasselbe Volume schreiben. Bei einem Update stoppt Kubernetes erst den alten Pod.
  • Die Readiness-Probe mit pg_isready sorgt dafür, dass Healthy erst kommt, wenn Postgres Verbindungen annimmt. Erst dann geht Argo CD zur nächsten Welle.

notes-api bekommt die Datenbank-URL und Welle 1. Die ganze Datei:

cat > deployment.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
  name: notes
  annotations:
    argocd.argoproj.io/sync-wave: "1"
spec:
  replicas: 2
  selector:
    matchLabels:
      app: notes
  template:
    metadata:
      labels:
        app: notes
    spec:
      containers:
        - name: api
          image: ghcr.io/thomaszachmann/notes-api:0.5.3
          ports:
            - containerPort: 8080
          env:
            - name: NOTES_API_KEY
              valueFrom:
                secretKeyRef:
                  name: notes-api
                  key: apiKey
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: notes-db
                  key: password
            - name: NOTES_DB_URL
              value: postgres://notes:$(DB_PASSWORD)@notes-db:5432/notes?sslmode=disable
          readinessProbe:
            httpGet:
              path: /healthz
              port: 8080
EOF

$(DB_PASSWORD) setzt Kubernetes selbst ein, weil die Variable weiter oben in derselben Liste steht. So steht das Passwort nur im Secret.

Fortschritt speichern? Kostenlos registrieren

Drill 2: Die Migration als PreSync-Hook

Das Schema legt notes-api migrate an. Der erste Gedanke: ein Job, der vor allem anderen läuft, also PreSync:

cat > migrate-job.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
  name: notes-migrate
  annotations:
    argocd.argoproj.io/hook: PreSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: ghcr.io/thomaszachmann/notes-api:0.5.3
          args: ["migrate"]
          env:
            - name: DB_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: notes-db
                  key: password
            - name: NOTES_DB_URL
              value: postgres://notes:$(DB_PASSWORD)@notes-db:5432/notes?sslmode=disable
EOF
cd ~/argo-lab/argocd-fleet
git add .
git commit -m "Postgres und Migration (PreSync)"
git push
argocd app get notes --refresh

Warte eine Minute:

sleep 60
argocd app get notes

Erwartet (gekürzt):

Sync Status:        OutOfSync from main (94cb48e)
Health Status:      Healthy

GROUP  KIND                   NAMESPACE  NAME           STATUS     HEALTH   HOOK     MESSAGE
batch  Job                    notes      notes-migrate  Running    Synced   PreSync  job.batch/notes-migrate created
       PersistentVolumeClaim  notes      notes-db       OutOfSync  Missing           
       Secret                 notes      notes-db       OutOfSync  Missing           
…
apps   Deployment             notes      notes-db       OutOfSync  Missing           

Der Sync hängt. Der Job läuft, alles andere fehlt noch. Warum, zeigen die Events:

kubectl -n notes get events --field-selector reason=Failed

Erwartet (gekürzt):

LAST SEEN   TYPE      REASON   OBJECT                    MESSAGE
6s          Warning   Failed   pod/notes-migrate-6dwjl   Error: secret "notes-db" not found

PreSync heißt wirklich vor allem, auch vor Welle -1. Das Secret mit dem Passwort gibt es noch nicht, und der Pod kann nicht starten. Argo CD wartet geduldig weiter. Du brichst den Sync ab:

argocd app terminate-op notes

Erwartet:

Application 'notes' operation terminating

Fortschritt speichern? Kostenlos registrieren

Drill 3: Die Migration als Sync-Hook in Welle 0

Die Migration gehört zwischen Datenbank und notes-api. Ein Sync-Hook ohne eigene Welle läuft in Welle 0:

sed -i "s/hook: PreSync/hook: Sync/" apps/notes/migrate-job.yaml
head -8 apps/notes/migrate-job.yaml

Erwartet:

apiVersion: batch/v1
kind: Job
metadata:
  name: notes-migrate
  annotations:
    argocd.argoproj.io/hook: Sync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
spec:
git commit -am "Migration als Sync-Hook"
git push
argocd app get notes --refresh
argocd app wait notes --operation --health --timeout 300

Erwartet (gekürzt):

…
GROUP  KIND                   NAMESPACE  NAME           STATUS     HEALTH   HOOK  MESSAGE
       Secret                 notes      notes-db       Synced                    secret/notes-db created
       PersistentVolumeClaim  notes      notes-db       Synced     Healthy        persistentvolumeclaim/notes-db created
       Service                notes      notes-db       Synced     Healthy        service/notes-db created
apps   Deployment             notes      notes-db       Synced     Healthy        deployment.apps/notes-db created
       Secret                 notes      notes-api      Synced                    secret/notes-api configured
       Service                notes      notes          Synced     Healthy        service/notes unchanged
batch  Job                    notes      notes-migrate  Succeeded  Synced   Sync  Reached expected number of succeeded pods
apps   Deployment             notes      notes          Synced     Healthy        deployment.apps/notes configured

Die Reihenfolge der Zeilen ist die Reihenfolge der Wellen: erst Postgres, dann die übrigen Objekte von Welle 0 mit dem Job, zuletzt notes-api. Was der Job getan hat:

kubectl -n notes logs job/notes-migrate
kubectl -n notes logs deploy/notes | grep store

Erwartet (gekürzt):

time=2026-11-14T08:41:11.202Z level=INFO msg="migration complete" table=notes
Found 2 pods, using pod/notes-75c5f54c4c-fzkvp
time=2026-11-14T08:41:16.323Z level=INFO msg="store ready" store=postgres

Fortschritt speichern? Kostenlos registrieren

Drill 4: Die Daten bleiben

curl -s -H "X-API-Key: lab-api-key-123" -d '{"text":"Hallo Argo CD"}' \
  localhost:30080/notes
kubectl -n notes rollout restart deploy/notes
kubectl -n notes rollout status deploy/notes
curl -s localhost:30080/notes

Erwartet (gekürzt):

{"id":"3fef3430-d55d-431b-bad7-c314189bd7a9","text":"Hallo Argo CD"}
…
[{"id":"3fef3430-d55d-431b-bad7-c314189bd7a9","text":"Hallo Argo CD"}]

Beide Pods sind neu, die Notiz ist noch da. rollout restart setzt eine Annotation, die nicht in Git steht. Self-Heal lässt sie deshalb in Ruhe (Tag 3, Drill 4).

kubectl -n notes exec deploy/notes-db -- \
  psql -U notes -d notes -c "select text from notes"

Erwartet:

     text      
---------------
 Hallo Argo CD
(1 row)

Fortschritt speichern? Kostenlos registrieren

Drill 5: Ein Smoke-Test als PostSync-Hook

Nach jedem Sync soll ein Job prüfen, ob notes-api antwortet:

cat > apps/notes/smoke-job.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
  name: notes-smoke
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: smoke
          image: curlimages/curl:8.17.0
          args: ["-sf", "http://notes/notes"]
EOF
git add .
git commit -m "Smoke-Test nach dem Sync"
git push
argocd app get notes --refresh | grep "Sync Status"

Erwartet:

Sync Status:        Synced to main (a4d8401)

Ausprobiert: Der Commit landet, die Application ist sofort Synced, aber kein Sync läuft und der Smoke-Test startet nie. Hooks zählen beim Vergleich nicht mit. Ein Commit, der nur einen Hook ändert, erzeugt also keine Abweichung, und automated hat nichts zu tun. Der Hook läuft erst beim nächsten echten Sync.

Du stößt ihn von Hand an:

argocd app sync notes

Erwartet (gekürzt):

…
batch  Job        notes   notes-migrate  Succeeded   Synced   Sync      Reached expected number of succeeded pods
batch  Job        notes   notes-smoke    Running     Synced   PostSync  job.batch/notes-smoke created
batch  Job        notes   notes-smoke    Succeeded   Synced   PostSync  Reached expected number of succeeded pods
…
Phase:              Succeeded
Message:            successfully synced (no more tasks)
kubectl -n notes get jobs

Erwartet:

NAME            STATUS     COMPLETIONS   DURATION   AGE
notes-migrate   Complete   1/1           5s         19s

notes-smoke ist schon wieder weg: HookSucceeded löscht den Job nach Erfolg. notes-migrate hat BeforeHookCreation und bleibt bis zum nächsten Sync stehen.

Fortschritt speichern? Kostenlos registrieren

Kontrollpunkt

argocd app get notes | grep -E "Sync Status|Health Status"

Erwartet: Synced und Healthy.

kubectl -n notes get pods

Erwartet: zwei Pods notes-…, einen Pod notes-db-…, alle Running, dazu notes-migrate-… mit Completed.

curl -s localhost:30080/notes

Erwartet: die Notiz Hallo Argo CD.

Challenge

Mach den Smoke-Test kaputt, indem er eine Adresse abfragt, die es nicht gibt. Was passiert mit dem Sync und mit notes-api? Repariere ihn danach wieder.

Hinweis: curl -f scheitert bei einem HTTP-Fehler. Schau nach der Reparatur genau auf die Meldung beim Job.

Lösung

sed -i "s#http://notes/notes#http://notes/gibtsnicht#" apps/notes/smoke-job.yaml
git commit -am "Smoke-Test kaputt"
git push
argocd app get notes --refresh
argocd app sync notes

Erwartet (gekürzt):

…  notes-smoke    Failed   Synced    PostSync  Job has reached the specified backoff limit
Phase:              Failed
Message:            one or more synchronization tasks completed unsuccessfully
argocd app get notes | grep -E "Sync Status|Health Status"
curl -s localhost:30080/version

Erwartet:

Sync Status:        Synced to main (ea5b39e)
Health Status:      Healthy
0.5.3

Der Sync gilt als gescheitert, notes-api läuft aber weiter. Ein PostSync-Hook kann nichts zurückdrehen, er meldet nur. Den fehlgeschlagenen Job lässt HookSucceeded stehen, damit du ihn untersuchen kannst. Jetzt die Reparatur:

sed -i "s#http://notes/gibtsnicht#http://notes/notes#" apps/notes/smoke-job.yaml
git commit -am "Smoke-Test repariert"
git push
argocd app get notes --refresh
argocd app sync notes

Erwartet (gekürzt):

…  notes-smoke  Failed  SyncFailed  PostSync  error when patching "/dev/shm/3202005619": Job.batch "notes-smoke" is invalid: spec.template: Invalid value: …: field is immutable
Phase:              Failed

Der alte, gescheiterte Job steht noch da. Argo CD versucht, ihn zu ändern, und das verbietet Kubernetes bei Jobs. Die Lösung sind beide Policies zusammen: vor dem nächsten Lauf löschen, nach Erfolg löschen.

cat > apps/notes/smoke-job.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
  name: notes-smoke
  annotations:
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded
spec:
  backoffLimit: 0
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: smoke
          image: curlimages/curl:8.17.0
          args: ["-sf", "http://notes/notes"]
EOF
git commit -am "Smoke-Test: alten Job vorher löschen"
git push
argocd app get notes --refresh
argocd app sync notes

Erwartet (gekürzt):

…
Phase:              Succeeded
Message:            successfully synced (no more tasks)

Fortschritt speichern? Kostenlos registrieren

Enterprise-Notiz

  • Migrationen als Hook sind praktisch, aber riskant: Ein Rollback per Argo CD dreht das Schema nicht zurück. Migrationen müssen deshalb abwärtskompatibel sein.
  • Ohne eigene Policy setzt Argo CD BeforeHookCreation. Wer eine andere angibt, ersetzt sie, statt sie zu ergänzen.
  • Postgres selbst gehört im Betrieb in einen Operator (CloudNativePG) oder einen verwalteten Dienst, nicht in ein Deployment mit einem Volume.