Skip to content

Keycloak Backups, Upgrade Gate, Drill and Rollback

Keycloak is every login on the platform, so a failed upgrade locks everyone out of Grafana, Gitea, Taskbase, OpenBao and Kubernetes OIDC. This page covers the pieces that make a new Keycloak image safe to apply without a person, following Renovate ADR §11:

  • the gate keycloak-preupgrade: Flux applies a new image only after the old one's database is backed up and the backup restored and checked;
  • the weekly restore drill keycloak-restore-drill;
  • the post-upgrade smoke check keycloak-smoke, which starts the suspended rollback keycloak-rollback when the new image does not come up.

None of them needs a Keycloak login: they work through the Kubernetes API, CNPG and Flux.

Piece Where Flux Kustomization
Gate Job, drill CronJob, scripts, RBAC components/keycloak/backup keycloak-preupgrade
Smoke and rollback Jobs components/keycloak/rollback keycloak-postupgrade
Order: keycloak dependsOn keycloak-preupgrade; keycloak-postupgrade dependsOn keycloak-preupgrade cluster/hetzner-mgmt/keycloak/kustomization.yaml —

The database itself, its daily base backup and WAL archiving are described under Database.

Versions

The "version" the gate and the smoke check follow is the deployed image, spec.image of the Keycloak CR in components/keycloak/base/keycloak-instance.yaml (harbor.prod.skatzi.com/skatzi/keycloak-kodexet:<tag>). Every new tag, whether an upstream Keycloak bump or a theme change, goes through the gate. The image appears in three places, which components/keycloak/backup/scripts/test_versions.py keeps equal in CI:

  • spec.image in keycloak-instance.yaml;
  • TARGET_IMAGE of the gate Job in components/keycloak/backup/job.yaml;
  • TARGET_IMAGE of the smoke Job in components/keycloak/rollback/job.yaml.

A change of spec.image alone would apply the new image without a backup, so the test fails the pull request. The upgrade guide has the workflow.

The Keycloak Operator (the keycloak-k8s-resources manifests vendored in components/keycloak/base/upstream/) is not gated: it migrates no data, and the rollback pins only the server image. A new operator that cannot run the old image would make the rollback fail; read its release notes before bumping it with a server version. Upstream says an operator from 26.6 on runs older images, but it no longer adds the Kubernetes service-account CA to their truststore ("Truststore initialization moved to the server" in the upgrading guide). Keycloak here verifies TLS only towards public endpoints (SMTP, Google, Facebook; the database URL sets no sslmode, so pgjdbc does not verify keycloak-db-rw), so a 26.4 image rolled back under it still works; if Keycloak ever has to trust the cluster CA, set truststore-paths in the CR first.

The PostgreSQL image of keycloak-db (imageName in components/keycloak/database/postgres-cluster.yaml) is not a version this gate follows: keycloak-db-image-preupgrade gates it, with Keycloak running, and keycloak-database dependsOn it (CloudNativePG: image gates). Never merge a new Keycloak image and a PostgreSQL image change in one push.

The upgrade gate

The Job keycloak-preupgrade (namespace keycloak, script preupgrade.sh) carries TARGET_IMAGE in its pod template and kustomize.toolkit.fluxcd.io/force: Enabled, so a new target image recreates it. The keycloak Kustomization dependsOn keycloak-preupgrade, whose health check is this Job: Flux applies the new image only after the Job has succeeded at the same Git revision.

Any other change to the Job's pod template recreates it as well, against the unchanged TARGET_IMAGE, such as a Renovate digest bump of its alpine/k8s image. Nothing upgrades then, so the gate passes without a backup when Keycloak already runs TARGET_IMAGE (step 2 below): Keycloak stays up, and keycloak-backup-latest keeps naming the backup taken before the last upgrade (owner's decision #3616, 2026-11-26). Until then such a change ran a full gate and stopped every login for a few minutes. The drill CronJob runs the same alpine/k8s image, and Renovate bumps them in the same pull request, so the next weekly drill is the first run of the new image. A change to scripts/ or templates/ alone does not recreate the Job: the keycloak-backup-scripts ConfigMap keeps a stable name.

  1. Fresh install (no Keycloak CR): nothing to back up, exits 0.
  2. Nothing to upgrade? When spec.image of the Keycloak CR equals TARGET_IMAGE, the gate logs Keycloak already runs <image>: nothing upgrades, nothing to back up and exits 0: it stops nothing and leaves keycloak-backup-latest as it is. The annotation platform.skatzi.com/preupgrade-force on the Keycloak CR overrides this (see Forcing a backup).
  3. Checks that keycloak-db reports ContinuousArchiving: True. Without WAL archiving the Backup cannot complete, so the gate fails here, before Keycloak is stopped.
  4. Stops writes: sets spec.instances: 0 on the Keycloak CR (Keycloak has no read-only mode) and waits up to 10 minutes for the operator's pods to go. Flux does not scale it back meanwhile: keycloak waits on this Job.
  5. Takes an on-demand CNPG Backup keycloak-db-preupgrade-<timestamp>, annotated with the running and the target image, and waits up to an hour for it to complete.
  6. Starts Keycloak again with the instance count it had. It also does this on any failure (an EXIT trap), so a failed gate leaves the old Keycloak running and blocks only the upgrade. Logins fail only between steps 4 and 6, typically a few minutes.
  7. Runs the restore check on that backup with the old image.
  8. Records the backup in ConfigMap keycloak/keycloak-backup-latest: BACKUP, BACKUP_ID, CREATED, IMAGE (the old image), TARGET_IMAGE and REALMS (the realms in the backup). The smoke check and the rollback read it. A forced backup then removes the force annotation.

A failed gate leaves keycloak-preupgrade not Ready, so the new image is not applied; the Flux alert reports it. The gate takes a backup only when Keycloak runs an image other than TARGET_IMAGE, or when the backup is forced. scripts/test_preupgrade.py runs it against a fake kubectl: it passes without stopping Keycloak when nothing upgrades, even with WAL archiving broken, and runs in full on a new image or a forced backup.

Forcing a backup of the running image

To back up the image Keycloak already runs, for a first backup on a new cluster or before a risky change the gate does not cover, annotate the Keycloak CR, then rerun the gate. Every login fails for a few minutes, as on an upgrade:

kubectl --context admin@mgmt-cluster -n keycloak annotate keycloaks.k8s.keycloak.org keycloak platform.skatzi.com/preupgrade-force=true
kubectl --context admin@mgmt-cluster -n keycloak delete job keycloak-preupgrade
flux --context admin@mgmt-cluster reconcile kustomization keycloak-preupgrade

The gate logs Forced by the annotation … and runs every step. Once the backup is verified and recorded it removes the annotation (the Role keycloak-preupgrade already may patch the CR, to scale Keycloak), so the next gate on the same image passes without a backup again. A failed gate leaves the annotation, so a retry is forced too. The annotation goes on the CR rather than the operator's StatefulSet, because the gate reads and scales Keycloak through the CR. Flux applies the CR with server-side apply and keeps an annotation that Git does not set and another field manager (here kubectl-annotate) owns. The rollback never restores a forced backup after an upgrade: the upgrade's gate replaces it with its own first.

The restore check

restore_check in lib.sh, shared by the gate and the drill:

  1. Restores keycloak-db into a throwaway CNPG Cluster in cnpg-drill (the scratch namespace with the backup-store ObjectStore), with the same PostgreSQL image and size. The gate restores its own Backup with recoveryTarget: {backupID, targetImmediate: true}; the drill restores the latest backup and all archived WAL. The copy has no WAL archiver, so it never writes into the store.
  2. Reads the realm names from the copy (SELECT … FROM realm) and fails if there are none.
  3. Starts the Keycloak image on the copy in a pod (templates/restore-pod.yaml): Keycloak as a sidecar, started the way the operator starts it (kc.sh start, which rebuilds for the options), with the copy's CNPG-generated credentials, a local cache and no hostname. The smoke container waits for its startup probe and runs smoke.py realms: every realm's /realms/<realm>/.well-known/openid-configuration must answer 200 with its own issuer.

The copy holds production's realms, including skatzi and emiliero, with their identity providers, clients and SMTP settings. The CiliumNetworkPolicy keycloak-restore lets its pods reach only DNS and the copies of keycloak-db in cnpg-drill. The throwaway Cluster and pod are deleted at the end, also on failure.

Weekly restore drill

The CronJob cnpg-drill/keycloak-restore-drill (Sundays 09:00 UTC, script drill.sh) runs the restore check on the latest backup with the image that runs in production (spec.image of the Keycloak CR). A pass is recorded in ConfigMap cnpg-drill/keycloak-drill (lastSuccess, pod, image, realms); this is what upgrade evidence cites. It replaces the database-only CronJob drill-keycloak. CNPGRestoreDrillFailed watches every CronJob in cnpg-drill, this one included, and fires when the last run failed or none passed in 8 days.

To run it by hand:

kubectl --context admin@mgmt-cluster -n cnpg-drill create job --from=cronjob/keycloak-restore-drill keycloak-drill-manual
kubectl --context admin@mgmt-cluster -n cnpg-drill logs -f job/keycloak-drill-manual

The smoke check

smoke.py passes when, within its deadline:

  • the operator's StatefulSet keycloak has the expected image in its pod template, and every replica (at least one) is updated and ready (upgrade and check modes); and
  • every realm in REALMS answers its discovery endpoint with 200 and its own issuer, through keycloak-service:8080. REALMS comes from the gate's keycloak-backup-latest; without it, master is checked.

The realm list comes from the backup, not from Git, so a realm created or deleted by hand is followed at the next gate run that takes a backup. The unit tests (test_smoke.py) run it against a fake Kubernetes API and Keycloak.

Post-upgrade smoke check and rollback

The Job keycloak-smoke (Kustomization keycloak-postupgrade) carries the same TARGET_IMAGE and is recreated with it. keycloak-postupgrade dependsOn keycloak-preupgrade, not keycloak: a failed upgrade leaves keycloak not Ready, and Flux never applies a dependent of a Kustomization that is not Ready.

smoke.py upgrade <image> waits up to 45 minutes for Keycloak to run the image and serve the realms. When it does, it deletes a finished keycloak-rollback, which Flux recreates suspended. When it does not, it resumes the suspended Job keycloak-rollback and fails, which fails keycloak-postupgrade; the Flux alert turns that into a task to revert the upgrade in Git.

The rollback Job

keycloak-rollback is deployed with suspend: true and kustomize.toolkit.fluxcd.io/ssa: IfNotPresent, so Flux never re-suspends a running rollback. Its init container runs rollback.sh:

  1. Guard, before anything changes: TARGET_IMAGE in keycloak-backup-latest must be the image the CR now carries, and the backup must be newer than the last gate run. Otherwise it refuses: on a fresh cluster, or when Keycloak already ran TARGET_IMAGE, the gate takes no backup, and the ConfigMap would still name an older one.
  2. Hold: suspends the keycloak Flux Kustomization and annotates it with platform.skatzi.com/keycloak-rollback-pin: <old image>, so Flux does not re-apply the failed image.
  3. Restores the gate's Backup (targetImmediate, so none of the new version's migrations are replayed) into the throwaway Cluster cnpg-drill/keycloak-rollback, and pg_dumps it. CNPG never restores over a running Cluster, and switching Keycloak to a new Cluster would leave it without backups (its serverName is taken) and be undone by Flux once the hold is lifted. The data therefore goes back into keycloak-db.
  4. Stops Keycloak (spec.instances: 0), renames the live database to keycloak_rollback_<timestamp>, creates an empty keycloak and pg_restores the dump into it. The realm names must match the backup's.
  5. Pins and resumes in one patch of the CR: spec.image back to the old image and the instance count it had, then waits for the StatefulSet to run it.

The Job's main container then runs smoke.py check <old image>. The Job succeeds only when the old Keycloak serves the backed-up realms again.

Lifting the hold: once Git carries the old image again (spec.image and both TARGET_IMAGEs reverted), Flux recreates the gate and then the smoke Job. Keycloak already runs the old image, so the gate passes without a backup, and keycloak-backup-latest keeps naming the backup that was restored. Seeing the pin equal to its target, the smoke Job removes the annotation and resumes the keycloak Kustomization. While Git still carries another image, the smoke Job fails without starting a rollback and names the image to revert to.

Data

  • Writes made between the gate and the rollback (logins, sessions, admin changes on the new version) are lost; the failed database stays as keycloak_rollback_<timestamp> in keycloak-db. Drop it once the cause is understood: kubectl --context admin@mgmt-cluster -n keycloak exec keycloak-db-1 -c postgres -- psql -c 'DROP DATABASE keycloak_rollback_<timestamp>'.
  • The pre-upgrade Backup objects stay in namespace keycloak and in the store under the CNPG retention (30 days).

RBAC

ServiceAccount Can
keycloak/keycloak-preupgrade get and patch the Keycloak CR keycloak (to scale it and remove its force annotation), list pods, get keycloak-db, create and get Backups, write keycloak-backup-latest; in cnpg-drill: create and delete copies and pods, exec into them (Role keycloak-restore)
cnpg-drill/keycloak-restore-drill get the Keycloak CR and keycloak-db; keycloak-restore in cnpg-drill, and write keycloak-drill
keycloak/keycloak-smoke get the StatefulSet keycloak; get, resume and delete the Job keycloak-rollback; get and patch the Kustomization flux-system/keycloak
keycloak/keycloak-rollback get and patch the Keycloak CR, get the StatefulSet, list pods, exec into keycloak-db-1, read keycloak-backup-latest and the gate Job; keycloak-restore in cnpg-drill; get and patch the Kustomization flux-system/keycloak

The rollback may exec into keycloak-db-1 only. keycloak-db has one instance, so that is its primary; the rollback checks it before stopping Keycloak.

Checking it on the cluster

kubectl --context admin@mgmt-cluster -n keycloak get job keycloak-preupgrade keycloak-smoke keycloak-rollback
kubectl --context admin@mgmt-cluster -n keycloak get configmap keycloak-backup-latest -o yaml
kubectl --context admin@mgmt-cluster -n cnpg-drill get cronjob keycloak-restore-drill
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap keycloak-drill -o yaml
kubectl --context admin@mgmt-cluster -n flux-system get kustomization keycloak -o jsonpath='{.spec.suspend} {.metadata.annotations}'

These need cluster access without Keycloak: use the Talos admin kubeconfig (admin@mgmt-cluster), not OIDC, while Keycloak is down.

Manual fallback

If the rollback refuses or fails, restore by hand with the admin kubeconfig:

  1. flux --context admin@mgmt-cluster suspend kustomization keycloak and kubectl --context admin@mgmt-cluster -n keycloak patch keycloaks.k8s.keycloak.org keycloak --type merge -p '{"spec":{"instances":0}}'.
  2. Restore the backup named in keycloak-backup-latest into a new Cluster as on the CloudNativePG page (serverName: keycloak, recoveryTarget: {backupID: <BACKUP_ID>, targetImmediate: true}), then copy it into keycloak-db as rollback.sh does (pg_dump of the copy, rename the live database, pg_restore).
  3. Set spec.image to IMAGE from the ConfigMap and spec.instances back, check the realms' discovery endpoints, revert Git, and flux --context admin@mgmt-cluster resume kustomization keycloak.