Tag 10: CRDs und Operatoren
Ziel: Du definierst einen eigenen Ressourcentyp, liest fremde CRDs mit
k explainund lässt einen Operator eine Postgres-Datenbank für notes-api betreiben. · Dauer: ca. 75 min · Voraussetzung: Tag 9
Briefing
CKAD: „Discover and use resources that extend Kubernetes (CRD, Operators)” (Application Environment, Configuration and Security, 25 %).
CRD --> neuer API-Typ (nur Daten, mit Schema)
Custom Resource --> ein Objekt dieses Typs (z. B. Cluster "notes-db")
Operator --> Controller im Cluster: beobachtet die CRs und baut
Pods, Services, Secrets, PVCs – und repariert sie
- In der Prüfung sind CRDs und Operatoren meist schon installiert. Deine Aufgabe: Typ finden, Felder lesen, Objekt anlegen.
mkdir -p ~/ckad/tag10 && cd ~/ckad/tag10
k create ns tag10
k config set-context --current --namespace=tag10Drill 1: Eine CRD anlegen
cat > backup-crd.yaml <<'EOF'
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: backups.tag10.example.com
spec:
group: tag10.example.com
scope: Namespaced
names:
plural: backups
singular: backup
kind: Backup
shortNames: ["bk"]
versions:
- name: v1
served: true
storage: true
additionalPrinterColumns:
- name: Schedule
type: string
jsonPath: .spec.schedule
- name: Target
type: string
jsonPath: .spec.target
- name: Days
type: integer
jsonPath: .spec.retentionDays
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
required: ["schedule", "target"]
properties:
schedule:
type: string
target:
type: string
enum: ["pvc", "s3"]
retentionDays:
type: integer
minimum: 1
maximum: 90
default: 7
EOF
k apply -f backup-crd.yaml
k api-resources --api-group=tag10.example.comErwartet:
customresourcedefinition.apiextensions.k8s.io/backups.tag10.example.com created
NAME SHORTNAMES APIVERSION NAMESPACED KIND
backups bk tag10.example.com/v1 true Backup
Der Name der CRD ist immer <plural>.<group>.
Ab jetzt kennt der API-Server den Typ – mit RBAC, k get,
-o yaml und --watch wie jeder eingebaute.
Fortschritt speichern? Kostenlos registrieren
Drill 2: Ein Objekt des neuen Typs
cat > nightly.yaml <<'EOF'
apiVersion: tag10.example.com/v1
kind: Backup
metadata:
name: notes-nightly
spec:
schedule: "0 2 * * *"
target: pvc
EOF
k apply -f nightly.yaml
k get bkErwartet:
backup.tag10.example.com/notes-nightly created
NAME SCHEDULE TARGET DAYS
notes-nightly 0 2 * * * pvc 7
retentionDays hat niemand gesetzt – der Default aus dem
Schema greift. Die Spalten kommen aus
additionalPrinterColumns.
k explain backup.specErwartet (gekürzt):
GROUP: tag10.example.com
KIND: Backup
VERSION: v1
...
FIELDS:
retentionDays <integer>
schedule <string> -required-
target <string> -required-
enum: pvc, s3
Fortschritt speichern? Kostenlos registrieren
Drill 3: Das Schema schützt
cat > broken.yaml <<'EOF'
apiVersion: tag10.example.com/v1
kind: Backup
metadata:
name: broken
spec:
schedule: "0 3 * * *"
target: tape
retentionDays: 365
EOF
k apply -f broken.yamlErwartet (umbrochen):
The Backup "broken" is invalid:
* spec.retentionDays: Invalid value: 365: spec.retentionDays in body should be less
than or equal to 90
* spec.target: Unsupported value: "tape": supported values: "pvc", "s3"
Unbekannte Felder lehnt der API-Server ebenfalls ab – Tippfehler fallen sofort auf:
k apply -f - <<'EOF'
apiVersion: tag10.example.com/v1
kind: Backup
metadata:
name: extra
spec:
schedule: "0 3 * * *"
target: s3
compress: true
EOFErwartet:
Error from server (BadRequest): error when creating "STDIN": Backup in version "v1"
cannot be handled as a Backup: strict decoding error: unknown field "spec.compress"
Eine CRD speichert nur Daten. Dass um 2 Uhr wirklich etwas gesichert
wird, müsste ein Controller erledigen, der Backup-Objekte
beobachtet – ein Operator.
Fortschritt speichern? Kostenlos registrieren
Drill 4: Einen Operator installieren
CloudNativePG betreibt Postgres in Kubernetes. Der Operator braucht nur 100 mCPU und 100–200 MiB – passt auf unsere Worker.
curl -sLO https://github.com/cloudnative-pg/cloudnative-pg/releases/download/v1.30.2/\
cnpg-1.30.2.yaml
grep '^kind:' cnpg-1.30.2.yaml | sort | uniq -cErwartet:
7 kind: ClusterRole
1 kind: ClusterRoleBinding
1 kind: ConfigMap
11 kind: CustomResourceDefinition
1 kind: Deployment
1 kind: MutatingWebhookConfiguration
1 kind: Namespace
1 kind: Service
1 kind: ServiceAccount
1 kind: ValidatingWebhookConfiguration
Vor dem Installieren lesen, was ins Cluster kommt: CRDs, clusterweite Rechte und zwei Admission-Webhooks (Tag 9).
k apply --server-side -f cnpg-1.30.2.yaml | tail -2
k rollout status deploy/cnpg-controller-manager -n cnpg-system --timeout=180s
k api-resources --api-group=postgresql.cnpg.ioErwartet (gekürzt):
mutatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-mutating-webhook-...
validatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-validating-webhoo...
deployment "cnpg-controller-manager" successfully rolled out
NAME SHORTNAMES APIVERSION NAMESPACED KIND
backups postgresql.cnpg.io/v1 true Backup
clusterimagecatalogs postgresql.cnpg.io/v1 false ClusterImag...
clusters postgresql.cnpg.io/v1 true Cluster
...
scheduledbackups postgresql.cnpg.io/v1 true ScheduledBackup
--server-side, weil die CRDs zu groß für die Annotation
von k apply sind. Und: backups gibt es jetzt
zweimal. k get bk ist eindeutig, sonst voll qualifizieren:
k get backups.tag10.example.com.
Fortschritt speichern? Kostenlos registrieren
Drill 5: Ein Postgres-Cluster per Custom Resource
Welche Felder braucht ein Cluster?
k explain cluster.spec.bootstrap.initdb | grep -E '^ (database|owner)'Erwartet:
database <string>
owner <string>
cat > notes-db.yaml <<'EOF'
apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: notes-db
spec:
instances: 2
storage:
size: 1Gi
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
memory: 512Mi
bootstrap:
initdb:
database: notes
owner: notes
EOF
k apply -f notes-db.yaml
k wait cluster/notes-db --for=condition=Ready --timeout=300s
k get cluster,pods,pvcErwartet (nach 1–3 Minuten, gekürzt):
cluster.postgresql.cnpg.io/notes-db created
cluster.postgresql.cnpg.io/notes-db condition met
NAME AGE INSTANCES READY STATUS ...
cluster.postgresql.cnpg.io/notes-db 62s 2 2 Cluster in healthy ...
NAME READY STATUS RESTARTS AGE
pod/notes-db-1 1/1 Running 0 43s
pod/notes-db-2 1/1 Running 0 13s
NAME STATUS VOLUME CAPACITY ... STORAGECLASS
persistentvolumeclaim/notes-db-1 Bound pvc-ed0… 1Gi ... local-path
persistentvolumeclaim/notes-db-2 Bound pvc-b7d… 1Gi ... local-path
Beim ersten Mal dauert es länger: Die Worker laden das Postgres-Image
ghcr.io/cloudnative-pg/postgresql:18.7-system-trixie.
Zwanzig Zeilen YAML, und der Operator hat Pods, PVCs, Replikation und – nächster Drill – Services und Secrets erzeugt.
Fortschritt speichern? Kostenlos registrieren
Drill 6: notes-api an die Datenbank hängen
k get svc,secret
k get secret notes-db-app -o jsonpath='{.data.uri}' | base64 -d | cut -c1-24; echoErwartet (gekürzt):
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/notes-db-r ClusterIP 10.100.129.255 <none> 5432/TCP 65s
service/notes-db-ro ClusterIP 10.111.159.47 <none> 5432/TCP 65s
service/notes-db-rw ClusterIP 10.109.4.4 <none> 5432/TCP 65s
NAME TYPE DATA AGE
secret/notes-db-app kubernetes.io/basic-auth 11 65s
...
postgresql://notes:ZlCcu
-rw zeigt immer auf den Primary, -ro auf
die Replicas. Das Secret enthält die fertige Verbindungs-URL samt vom
Operator erzeugtem Passwort (oben gekürzt) – genau das, was notes-api in
NOTES_DB_URL erwartet:
cat > notes.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata:
name: notes
spec:
initContainers:
- name: migrate
image: 172.16.0.126:30500/notes-api:1.0
args: ["migrate"]
env:
- name: NOTES_DB_URL
valueFrom:
secretKeyRef: {name: notes-db-app, key: uri}
containers:
- name: notes
image: 172.16.0.126:30500/notes-api:1.0
env:
- name: NOTES_API_KEY
value: lab-key-123
- name: NOTES_DB_URL
valueFrom:
secretKeyRef: {name: notes-db-app, key: uri}
EOF
k apply -f notes.yaml
k wait --for=condition=Ready pod/notes --timeout=90s
k logs notes -c migrate
k exec notes -- wget -qO- --header 'X-API-Key: lab-key-123' \
--post-data '{"text":"liegt in Postgres"}' http://localhost:8080/notesErwartet (gekürzt):
pod/notes created
pod/notes condition met
time=... level=INFO msg="migration complete" table=notes
Defaulted container "notes" out of: notes, migrate (init)
{"id":"d4f216d7-9bdc-41a6-a101-df4eed8a672e","text":"liegt in Postgres"}
lab-key-123 ist ein reiner Lab-Wert. Die Notiz liegt
wirklich in der Datenbank:
k exec notes-db-1 -c postgres -- psql -U postgres -d notes -tc 'select text from notes'Erwartet:
liegt in Postgres
Fortschritt speichern? Kostenlos registrieren
Drill 7: Der Operator repariert
k get pods -L cnpg.io/instanceRole
k delete pod notes-db-1Erwartet (gekürzt):
NAME READY STATUS RESTARTS AGE INSTANCEROLE
notes 1/1 Running 0 11s
notes-db-1 1/1 Running 0 62s primary
notes-db-2 1/1 Running 0 32s replica
pod "notes-db-1" deleted from tag10 namespace
Ein paar Sekunden später:
k get cluster notes-db
k get pods -L cnpg.io/instanceRoleErwartet (gekürzt):
NAME AGE INSTANCES READY STATUS PRIMARY
notes-db 2m 2 2 Cluster in healthy state notes-db-2
NAME READY STATUS RESTARTS AGE INSTANCEROLE
notes 1/1 Running 0 86s
notes-db-1 1/1 Running 0 16s replica
notes-db-2 1/1 Running 0 107s primary
Kein Deployment und kein StatefulSet – der Operator hat die Replica
befördert, den Pod neu gebaut und den Service notes-db-rw
umgehängt. notes-api schreibt weiter:
k exec notes -- wget -qO- --header 'X-API-Key: lab-key-123' \
--post-data '{"text":"nach Failover"}' http://localhost:8080/notesErwartet (gekürzt):
{"id":"f6616d76-38af-4e8b-8f68-60a73f4338f1","text":"nach Failover"}
Fortschritt speichern? Kostenlos registrieren
Übung: Speed-Drills
- Liste alle CRDs der Gruppe
postgresql.cnpg.iomit Namen. Zeitziel: 15 s - Zeige die Felder von
spec.storageeines CNPG-Cluster. Zeitziel: 20 s - Gib nur den Namen des aktuellen Primary von
notes-dbaus. Zeitziel: 30 s - Lege einen
Backup(Gruppetag10.example.com) namensweeklymit Ziels3, 30 Tagen und Zeitplan0 4 * * 0an. Zeitziel: 60 s
Lösung
k get crd -o name | grep postgresql.cnpg.io
k explain cluster.spec.storage | grep -E '^ [a-z]'
k get cluster notes-db -o jsonpath='{.status.currentPrimary}{"\n"}'
k apply -f - <<'EOF'
apiVersion: tag10.example.com/v1
kind: Backup
metadata:
name: weekly
spec:
schedule: "0 4 * * 0"
target: s3
retentionDays: 30
EOF
k get bkErwartet (gekürzt):
customresourcedefinition.apiextensions.k8s.io/backups.postgresql.cnpg.io
...
pvcTemplate <Object>
resizeInUseVolumes <boolean>
size <string>
notes-db-2
backup.tag10.example.com/weekly created
NAME SCHEDULE TARGET DAYS
notes-nightly 0 2 * * * pvc 7
weekly 0 4 * * 0 s3 30
Fortschritt speichern? Kostenlos registrieren
Kontrollpunkt
k get crd backups.tag10.example.com -o jsonpath='{.spec.versions[0].name}{"\n"}'Erwartet: v1
k get cluster notes-db -o jsonpath='{.status.readyInstances}{"\n"}'Erwartet: 2
k exec notes -- wget -qO- http://localhost:8080/notesErwartet: beide Notizen als JSON-Liste,
"liegt in Postgres" und "nach Failover".
Challenge
Backups auf pvc dürfen höchstens 14 Tage aufbewahrt
werden, auf s3 bis 90. Erzwinge das in der CRD selbst –
ohne Webhook.
Hinweis: x-kubernetes-validations mit
einer CEL-Regel unter spec im Schema.
Lösung
In backup-crd.yaml unter spec: direkt nach
dessen type: object einfügen:
x-kubernetes-validations:
- rule: "self.target == 's3' || self.retentionDays <= 14"
message: "pvc-Backups höchstens 14 Tage"k apply -f backup-crd.yamlErwartet:
customresourcedefinition.apiextensions.k8s.io/backups.tag10.example.com configured
k patch bk notes-nightly --type=merge -p '{"spec":{"retentionDays":30}}'
k patch bk weekly --type=merge -p '{"spec":{"retentionDays":60}}'Erwartet:
The Backup "notes-nightly" is invalid: spec: Invalid value: pvc-Backups höchstens 14
Tage
backup.tag10.example.com/weekly patched
Aufräumen – erst die Datenbank, solange der Operator noch läuft, dann den Operator und die eigene CRD:
k config set-context --current --namespace=default
k delete ns tag10
k delete -f cnpg-1.30.2.yaml | tail -2
k delete crd backups.tag10.example.com
k get crd | grep -cE 'cnpg|tag10'Erwartet (gekürzt):
namespace "tag10" deleted
mutatingwebhookconfiguration.admissionregistration.k8s.io "cnpg-mutating-webhook-..."
validatingwebhookconfiguration.admissionregistration.k8s.io "cnpg-validating-webhoo..."
customresourcedefinition.apiextensions.k8s.io "backups.tag10.example.com" deleted
0
Fortschritt speichern? Kostenlos registrieren
Prüfungstipp
- Unbekannter Typ in der Aufgabe?
k api-resources | grep -i <name>, dannk explain <kind>.specEbene für Ebene – schneller als jede Doku. - Gleiche Namen in zwei Gruppen: voll qualifizieren
(
backups.tag10.example.com) oderapiVersionim YAML genau prüfen. - Custom Resources sind normale API-Objekte:
k get,k describe,k edit,k deleteundk wait --for=condition=…funktionieren wie gewohnt.
Enterprise-Notiz
- Operatoren bringen clusterweite Rechte und Webhooks mit – vor der Installation die ClusterRoles lesen und die Version pinnen (Helm-Chart oder Manifest aus Git).
- Ein ausgefallener Webhook-Pod kann das Anlegen von Objekten blockieren; Operatoren brauchen Monitoring wie jede andere Anwendung.
- CRD-Upgrades mit neuen Versionen brauchen Conversion – gehört in den Wartungsplan.
- Datenbank-Operatoren ersetzen kein Backup-Konzept: CloudNativePG sichert erst mit konfiguriertem Objektspeicher (z. B. S3) wirklich weg.