Keycloak upgrade guide¶
This guide covers every kind of change you might need to ship for Keycloak:
- Theme changes (CSS, logo, copy)
- Keycloak version bumps (upstream)
- Keycloak CR / runtime configuration
- Realm settings (clients, flows, themes, signup)
- Rollback
- Data safety notes
All changes land in the Skatzi/platform repo. Flux on the mgmt-cluster reconciles components/keycloak/ into the keycloak namespace.
1. Theme changes¶
Any file under components/keycloak/theme/kodexet/ (CSS, logo, HTML overrides, theme.properties, translations) is baked into the Docker image at build time. Shipping a theme change is therefore a new image tag + bump on the Keycloak CR.
Workflow¶
-
Edit the theme on a branch, e.g. tweak
theme/kodexet/login/resources/css/styles.css. -
Pick the next image tag. Tags follow
vMAJOR.MINOR.PATCH. Check what's currently deployed:grep 'image:' components/keycloak/base/keycloak-instance.yaml # image: harbor.prod.skatzi.com/skatzi/keycloak-kodexet:v1.0.1Bump patch for pure theme tweaks, minor for bigger reworks.
-
Bump the image reference in
components/keycloak/base/keycloak-instance.yaml, and the same image inTARGET_IMAGEofcomponents/keycloak/backup/job.yaml(the upgrade gate) andcomponents/keycloak/rollback/job.yaml(the smoke check). CI'stest_versions.pyfails the pull request when the three differ; see Keycloak backups. -
Commit, push the branch, and tag its head. The Gitea CI workflow
.gitea/workflows/ci-keycloak.yamltriggers on tags matchingkeycloak-v*.*.*and builds from the tagged commit, so the image can be built before the pull request is merged:git add components/keycloak/ && git commit -m "fix(keycloak): <what changed>" git push origin <branch> git tag keycloak-v1.0.2 git push origin keycloak-v1.0.2The tag push kicks Kaniko — it builds from
components/keycloak/Dockerfileand pushes:harbor.prod.skatzi.com/skatzi/keycloak-kodexet:v1.0.2harbor.prod.skatzi.com/skatzi/keycloak-kodexet:latest
-
Wait for the image to land in Harbor (check the Gitea Actions tab or Harbor UI) before merging. If Flux applies an image that does not exist, Keycloak cannot start, the smoke check fails and the rollback restores the database.
-
Merge the pull request. Flux first runs the upgrade gate: Keycloak stops for the few minutes of the backup, so logins fail briefly, then runs the old image again while the backup is restored and checked. Only then does Flux apply the new
image:, and the operator recreates the StatefulSet. Watch the gate and the rollout:kubectl --context admin@mgmt-cluster -n keycloak logs -f job/keycloak-preupgrade kubectl --context admin@mgmt-cluster -n keycloak get pod -w kubectl --context admin@mgmt-cluster -n keycloak logs keycloak-0 -fThe first boot runs
kc.sh buildagain (becausestartOptimized: false) — expect a minute of startup beforeListening on http://0.0.0.0:8080appears. The smoke Jobkeycloak-smokethen checks that the new image runs and every realm answers; if not, it starts the rollback.
Activating the theme in a realm¶
Adding a theme to the image does not automatically assign it to a realm. Do that once in the admin console:
Admin console → select realm → Realm Settings → Themes → Login Theme:
kodexet→ Save.
The same applies for Account / Email / Admin themes if they ever get their own variants.
2. Keycloak version bump¶
Upstream releases: https://www.keycloak.org/docs/latest/release_notes/index.html. Always read the release notes for breaking changes before bumping.
Workflow¶
-
Bump the base image in
components/keycloak/Dockerfile: -
Bump the Keycloak Operator too if required by the new version: replace the files in
components/keycloak/base/upstream/with the manifests thatkubernetes/kustomization.ymlof the new tag inkeycloak/keycloak-k8s-resourceslists, unchanged, and update the version in the comment above them inkustomization.yaml. Add any new manifest to that list too: 26.8 added theKeycloakOIDCClientandKeycloakSAMLClientCRDs, and the operator runs a controller for each. Leave out upstream'skustomization.ymlandcluster-wide/; ourkustomization.yamlsets the namespace and patches the bindings itself. They are vendored, not fetched by URL, so a GitHub timeout cannot fail thekeycloakKustomization.Do this in a separate, later pull request, once Keycloak runs the new image. Upstream's order for custom images is the server image first under the old operator, then the operator (Upgrading an Operator). Keeping the operator unchanged during the image bump also keeps the rollback intact, because the old operator still runs the old image. A new operator brings new CRDs, so run the runbook's Pre-flight for CRD-bringing operators for it, and check in its release notes that it still runs the previous image, since the rollback pins that image under the new operator.
-
Bump the image tag in
keycloak-instance.yamland bothTARGET_IMAGEs (use a minor bump when the upstream minor changes, e.g.v1.1.0). -
Follow the rest of the theme-change workflow from step 4 onwards.
Checklist for major version bumps¶
- Read upstream release notes end-to-end
- Check the last restore drill passed (
kubectl --context admin@mgmt-cluster -n cnpg-drill get configmap keycloak-drill); the gate takes the backup itself - Check for deprecated server options in
additionalOptionsof the CR - Verify theme
parent=keycloak.v2still resolves (the upstream theme tree is version-specific) - Validate the admin console loads and existing clients still work before closing the change
Before a bump that changes admin access¶
Some releases change who may call the Admin REST API: 26.8.2 accepts only tokens with the kc-admin-api client scope (Admin REST API for agents). Its migration creates the scope, so it can be assigned only after the new image runs, and until then taskbase-service gets 401 and Taskbase rejects every authenticated request. For such a bump:
- Plan who assigns the scope right after
keycloak-smokepasses: a person in the admin console, or an agent with themasteradmin login. - If the plan uses the
masterlogin, test it before merging. The bootstrap Secret can be stale. - Plan the order of the merge run's last steps:
resume_organizationneeds Taskbase, so it works only aftertaskbase-servicehas its access back.
Test the master admin login¶
The login is read-only. It sends the password from the Secret by stdin, so it is never printed:
kubectl --context admin@mgmt-cluster -n keycloak get secret keycloak-initial-admin -o jsonpath='{.data.password}' | base64 -d \
| kubectl --context admin@mgmt-cluster -n keycloak exec -i keycloak-0 -- \
/opt/keycloak/bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user temp-admin
Invalid user credentials [invalid_grant] means the Secret no longer holds temp-admin's password: do not merge on a plan that needs this login. This is the login the merge run of 2026-11-18 used (#1260 upgrade evidence); it has not been run from the machine that wrote this page.
3. Keycloak CR / runtime configuration¶
Changes to components/keycloak/base/keycloak-instance.yaml do not require a new image — the operator picks up CR changes and rolls the pod on its own. No tag push needed.
Common fields¶
| Field | What it does |
|---|---|
spec.instances |
Replica count. Keep at 1 unless HA is deliberately configured. |
spec.db.* |
Database vendor/host/secret. Changing vendor or host requires a restart and is a data-migration exercise. |
spec.hostname.hostname |
Public FQDN. Must match the HTTPRoute and TLS cert. |
spec.proxy.headers |
Keep at xforwarded — Cilium Gateway terminates TLS and forwards headers. |
spec.additionalOptions |
Any Keycloak server option (kc.sh start --<name>=<value>). Build-time options force a rebuild on pod boot. |
spec.startOptimized |
Must stay false as long as additionalOptions contains build-time options, otherwise the pod crash-loops with build time options have values that differ from what is persisted. |
Ship the change the normal way:
git add components/keycloak/base/keycloak-instance.yaml
git commit -m "chore(keycloak): <what changed>"
git push origin main
Flux reconciles within a minute, the operator rolls the pod, done.
4. Realm settings¶
The realm CRDs are disaster-recovery snapshots only — they do not drive live config. Live changes are made in the admin console, or for skatzi through the Admin REST API with ops-agent-realm-admin (see Admin REST API for agents). Either way, update the YAML in base/*-realm.yaml to match so the DR snapshot stays current.
Workflow for any realm change¶
-
Make the change live, in the admin console or through the Admin REST API:
- Admin console:
https://keycloak.prod.skatzi.com→ admin login → select the realm (skatzioremiliero), change the setting (themes, login flows, identity providers, clients, registration, etc.) and save. - Admin REST API (realm
skatzionly): get a token forops-agent-realm-adminwith the client-credentials grant and call/admin/realms/skatzi/..., as Admin REST API for agents describes. Read the current setting first and never print the credentials.
- Admin console:
-
Verify end-to-end — log in with an affected client before mirroring to YAML.
-
Mirror the change into the DR snapshot in
components/keycloak/base/<realm>-realm.yaml. Inskatzi-realm.yaml, keep every flow inauthenticationFlows, every entry inauthenticatorConfigand every scope inclientScopes, the built-in ones included, and give each client itsdefaultClientScopesandoptionalClientScopes, as Admin REST API for agents explains. Example — enabling self-service registration: -
Commit as
chore(keycloak): update <realm> realm DR snapshotand push.
Assign a default client scope without an admin login¶
Recovery step only. Use it when a client must get a default client scope now, for example kc-admin-api after the 26.8.2 migration so that Taskbase works again, and no admin login can do it: the master login fails, no person can use the admin console in time, and the client's own realm admin has lost access too. Otherwise use the Admin REST API (PUT /admin/realms/<realm>/clients/<id>/default-client-scopes/<scope-id>) or the admin console (Clients → client → Client scopes → Add → Default). The write goes past Keycloak, and Keycloak must be restarted to see it.
It was used once, on 2026-11-18, to give kc-admin-api to skatzi/taskbase-service, skatzi/ops-agent-realm-admin and emiliero/emiliero-admin (incident report, PR #1537). The commands below do the same. The SQL was run on 2026-11-18 against a local PostgreSQL with copies of the four tables it uses, not against keycloak-db; the kubectl commands have not been run from the machine that wrote this page.
-
Have a fresh, verified backup. Right after an upgrade, that is the gate's backup:
kubectl --context admin@mgmt-cluster -n keycloak logs job/keycloak-preupgradeends withBackup keycloak-db-preupgrade-<timestamp> … verified. A gate that logsnothing upgradestook none. Otherwise force a gate backup or take an on-demand backup and wait forcompleted(Data safety notes). -
Find the primary (
keycloak-db-1on 2026-11-18): -
Check read-only that each client and its realm's scope exist and the client lacks the scope. Edit the list of
(realm, client)pairs and the scope name for your case:kubectl --context admin@mgmt-cluster -n keycloak exec -i "$PRIMARY" -c postgres -- psql -d keycloak <<'SQL' SELECT r.name AS realm, c.client_id, s.name AS scope, x.default_scope FROM client c JOIN realm r ON r.id = c.realm_id JOIN client_scope s ON s.realm_id = r.id AND s.name = 'kc-admin-api' LEFT JOIN client_scope_client x ON x.client_id = c.id AND x.scope_id = s.id WHERE (r.name, c.client_id) IN (('skatzi', 'taskbase-service'), ('skatzi', 'ops-agent-realm-admin'), ('emiliero', 'emiliero-admin')); SQLExpect one row per client, with
default_scopeempty. A missing row means a wrong name or a missing scope: stop. -
Insert the rows in one guarded block. It raises, and so writes nothing, unless it inserts exactly the expected number of rows (3 here):
kubectl --context admin@mgmt-cluster -n keycloak exec -i "$PRIMARY" -c postgres -- psql -d keycloak -v ON_ERROR_STOP=1 <<'SQL' DO $$ DECLARE inserted integer; BEGIN INSERT INTO client_scope_client (client_id, scope_id, default_scope) SELECT c.id, s.id, true FROM client c JOIN realm r ON r.id = c.realm_id JOIN client_scope s ON s.realm_id = r.id AND s.name = 'kc-admin-api' WHERE (r.name, c.client_id) IN (('skatzi', 'taskbase-service'), ('skatzi', 'ops-agent-realm-admin'), ('emiliero', 'emiliero-admin')) AND NOT EXISTS (SELECT 1 FROM client_scope_client x WHERE x.client_id = c.id AND x.scope_id = s.id); GET DIAGNOSTICS inserted = ROW_COUNT; IF inserted <> 3 THEN RAISE EXCEPTION 'expected 3 rows, would insert %; nothing written', inserted; END IF; RAISE NOTICE 'inserted %', inserted; END $$; SQLExpected output:
NOTICE: inserted 3. Any other count ends inERROR: expected 3 rows, would insert <n>; nothing written, and the table is unchanged.default_scopetruemakes it a default scope, the same shape the migration wrote foradmin-cli. Keep the guard aRAISE: on 2026-11-18 a first guard written asCASE … (1/0)aborted withdivision by zerobefore writing anything, because PostgreSQL folds the constant1/0before it runs the query. -
Restart Keycloak. Its realm cache does not see the new rows: on 2026-11-18, tokens taken after the insert still had
scope: email profileand got 401. The restart takes about 1 minute, during which every Keycloak login fails: -
Verify each client. A client-credentials token has the scope in
scopeandhttps://keycloak.prod.skatzi.com/admin/realms/<realm>inaud, andGET /admin/realms/<realm>/users?max=1with it returns 200. Taskbase recovers by itself within the 300 s its cached token may still live (Admin REST API for agents). -
Mirror the change into the DR snapshot (step 3 of the workflow);
kc-admin-apiis already there (#3361).
Why not drive realms from the CRD?¶
The Keycloak Operator's KeycloakRealmImport resource only imports a realm the first time — subsequent CRD edits are silently ignored against a live realm. Attempting to drive live config from YAML therefore produces silent drift. The DR snapshots exist so that if we ever had to recreate the database from scratch, the realm imports would rebuild skatzi and emiliero to their documented states. Deleting an import does not delete its live realm.
Common realm-change pitfalls¶
- "Users get sent straight to Google" — check Authentication → Flows → Browser → Identity Provider Redirector → config. If
Default Identity Provideris set, the login page is skipped. Clear it to get the normal login form back. - "Theme changes don't apply" — make sure the theme is both in the image (step 1) and assigned on the realm (Realm Settings → Themes).
- "Google login fails after changing redirect URIs" — mirror the same URIs in the Google Cloud OAuth client, not just in Keycloak.
5. Rollback¶
Rollback an image¶
A new image that does not come up is rolled back automatically: the smoke check starts keycloak-rollback, which restores the gate's backup and pins the old image without a login (Keycloak backups). Revert the change in Git afterwards, so the hold is lifted. To go back by hand from an image that does come up:
# In keycloak-instance.yaml
spec:
image: harbor.prod.skatzi.com/skatzi/keycloak-kodexet:v1.0.1 # previous tag
Revert TARGET_IMAGE in both Jobs with it, and merge — Flux runs the gate and rolls back to the previous image. The database stays as the newer image left it, so this only works when the newer version made no migration the older one cannot read; otherwise restore the gate's backup as the rollback Job does. All images stay in Harbor; nothing is garbage-collected automatically.
Rollback a CR change¶
git revert <sha> the offending commit, push, Flux reconciles the previous state.
Rollback a realm change¶
There is no automated rollback. Either:
- Undo the change manually in the admin console (preferred for small changes), or
- Restore
keycloak-dbto a point in time before the change into a new Cluster and switch Keycloak to it (heavy, loses all user activity since that point; see Data safety notes).
6. Data safety notes¶
Keycloak's state lives in the CNPG Cluster keycloak-db in the keycloak namespace (see Database). It is backed up continuously to the backup store (WAL plus a daily base backup) and restored in a weekly drill. It is not touched by:
- Image bumps (theme or upstream version), except for the upgrade's own database migrations. The upgrade gate backs the database up before every new image and the rollback restores that backup
- CR changes (
keycloak-instance.yaml) - Realm DR snapshot updates (the YAML only applies on initial import)
It is at risk from:
- Deleting the
keycloak-dbCluster or its PVC. Flux does this ifcomponents/keycloak/databaseleaves thekeycloak-databaseKustomization; the backups stay in the store. - A PostgreSQL major version bump of
imageNamewithout a dump/restore or a CNPG major upgrade KeycloakRealmImportre-import if the operator is ever changed to reconcile continuously — check release notes before upgrading the operator
Before a storage change or anything else the gate does not cover, take an on-demand backup and wait for it to complete:
kubectl --context admin@mgmt-cluster -n keycloak create -f - <<'YAML'
apiVersion: postgresql.cnpg.io/v1
kind: Backup
metadata:
generateName: keycloak-db-manual-
spec:
cluster:
name: keycloak-db
method: plugin
pluginConfiguration:
name: barman-cloud.cloudnative-pg.io
YAML
kubectl --context admin@mgmt-cluster -n keycloak get backups.postgresql.cnpg.io # PHASE completed
Restoring is described on the CloudNativePG page (serverName: keycloak).