Skip to content

Keycloak upgrade guide

This guide covers every kind of change you might need to ship for Keycloak:

  1. Theme changes (CSS, logo, copy)
  2. Keycloak version bumps (upstream)
  3. Keycloak CR / runtime configuration
  4. Realm settings (clients, flows, themes, signup)
  5. Rollback
  6. 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

  1. Edit the theme on a branch, e.g. tweak theme/kodexet/login/resources/css/styles.css.

  2. 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.1
    

    Bump patch for pure theme tweaks, minor for bigger reworks.

  3. Bump the image reference in components/keycloak/base/keycloak-instance.yaml, and the same image in TARGET_IMAGE of components/keycloak/backup/job.yaml (the upgrade gate) and components/keycloak/rollback/job.yaml (the smoke check). CI's test_versions.py fails the pull request when the three differ; see Keycloak backups.

    spec:
      image: harbor.prod.skatzi.com/skatzi/keycloak-kodexet:v1.0.2
    
  4. Commit, push the branch, and tag its head. The Gitea CI workflow .gitea/workflows/ci-keycloak.yaml triggers on tags matching keycloak-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.2
    

    The tag push kicks Kaniko — it builds from components/keycloak/Dockerfile and pushes:

    • harbor.prod.skatzi.com/skatzi/keycloak-kodexet:v1.0.2
    • harbor.prod.skatzi.com/skatzi/keycloak-kodexet:latest
  5. 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.

  6. 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 -f
    

    The first boot runs kc.sh build again (because startOptimized: false) — expect a minute of startup before Listening on http://0.0.0.0:8080 appears. The smoke Job keycloak-smoke then 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

  1. Bump the base image in components/keycloak/Dockerfile:

    FROM quay.io/keycloak/keycloak:26.5.0
    
  2. Bump the Keycloak Operator too if required by the new version: replace the files in components/keycloak/base/upstream/ with the manifests that kubernetes/kustomization.yml of the new tag in keycloak/keycloak-k8s-resources lists, unchanged, and update the version in the comment above them in kustomization.yaml. Add any new manifest to that list too: 26.8 added the KeycloakOIDCClient and KeycloakSAMLClient CRDs, and the operator runs a controller for each. Leave out upstream's kustomization.yml and cluster-wide/; our kustomization.yaml sets the namespace and patches the bindings itself. They are vendored, not fetched by URL, so a GitHub timeout cannot fail the keycloak Kustomization.

    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.

  3. Bump the image tag in keycloak-instance.yaml and both TARGET_IMAGEs (use a minor bump when the upstream minor changes, e.g. v1.1.0).

  4. 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 additionalOptions of the CR
  • Verify theme parent=keycloak.v2 still 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:

  1. Plan who assigns the scope right after keycloak-smoke passes: a person in the admin console, or an agent with the master admin login.
  2. If the plan uses the master login, test it before merging. The bootstrap Secret can be stale.
  3. Plan the order of the merge run's last steps: resume_organization needs Taskbase, so it works only after taskbase-service has 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

  1. 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 (skatzi or emiliero), change the setting (themes, login flows, identity providers, clients, registration, etc.) and save.
    • Admin REST API (realm skatzi only): get a token for ops-agent-realm-admin with 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.
  2. Verify end-to-end — log in with an affected client before mirroring to YAML.

  3. Mirror the change into the DR snapshot in components/keycloak/base/<realm>-realm.yaml. In skatzi-realm.yaml, keep every flow in authenticationFlows, every entry in authenticatorConfig and every scope in clientScopes, the built-in ones included, and give each client its defaultClientScopes and optionalClientScopes, as Admin REST API for agents explains. Example — enabling self-service registration:

    spec:
      realm:
        registrationAllowed: true
        resetPasswordAllowed: true
    
  4. Commit as chore(keycloak): update <realm> realm DR snapshot and 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.

  1. 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-preupgrade ends with Backup keycloak-db-preupgrade-<timestamp> … verified. A gate that logs nothing upgrades took none. Otherwise force a gate backup or take an on-demand backup and wait for completed (Data safety notes).

  2. Find the primary (keycloak-db-1 on 2026-11-18):

    PRIMARY=$(kubectl --context admin@mgmt-cluster -n keycloak get cluster keycloak-db -o jsonpath='{.status.currentPrimary}')
    
  3. 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'));
    SQL
    

    Expect one row per client, with default_scope empty. A missing row means a wrong name or a missing scope: stop.

  4. 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 $$;
    SQL
    

    Expected output: NOTICE: inserted 3. Any other count ends in ERROR: expected 3 rows, would insert <n>; nothing written, and the table is unchanged. default_scope true makes it a default scope, the same shape the migration wrote for admin-cli. Keep the guard a RAISE: on 2026-11-18 a first guard written as CASE … (1/0) aborted with division by zero before writing anything, because PostgreSQL folds the constant 1/0 before it runs the query.

  5. Restart Keycloak. Its realm cache does not see the new rows: on 2026-11-18, tokens taken after the insert still had scope: email profile and got 401. The restart takes about 1 minute, during which every Keycloak login fails:

    kubectl --context admin@mgmt-cluster -n keycloak delete pod keycloak-0
    kubectl --context admin@mgmt-cluster -n keycloak get pod keycloak-0 -w   # until READY 1/1
    
  6. Verify each client. A client-credentials token has the scope in scope and https://keycloak.prod.skatzi.com/admin/realms/<realm> in aud, and GET /admin/realms/<realm>/users?max=1 with it returns 200. Taskbase recovers by itself within the 300 s its cached token may still live (Admin REST API for agents).

  7. Mirror the change into the DR snapshot (step 3 of the workflow); kc-admin-api is 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 Provider is 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-db to 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-db Cluster or its PVC. Flux does this if components/keycloak/database leaves the keycloak-database Kustomization; the backups stay in the store.
  • A PostgreSQL major version bump of imageName without a dump/restore or a CNPG major upgrade
  • KeycloakRealmImport re-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).