Cloning a Keycloak realm? This tool saves hours of UUID rewrites

Duplicating a Keycloak realm on the same server sounds straightforward—until Keycloak rejects the import with a primary-key collision. A new open-source tool automates the manual and error-prone process of regenerating every UUID so the clone can coexist safely with the original.
The UUID trap in realm cloning
Keycloak exports realms as full snapshots of the database, complete with every role, client, user, protocol mapper, and authentication flow carrying the same internal UUIDs. Renaming the realm in the export merely changes its display name; it does not touch the dozens or hundreds of UUIDs referenced throughout the file. Re-importing such a file into the same instance triggers duplicate-key errors because the primary keys already exist. This limitation is documented upstream in keycloak/keycloak#24770, where the exporter is not designed to produce an import-anywhere-including-here artifact.
Manual fixes don’t scale
Theoretically, you could open the JSON, replace every UUID with a fresh one, and carefully map each old UUID to the new one to preserve cross-references. For a small realm this is tedious but feasible. For a production setup with custom roles, multiple clients, identity providers, and authentication flows, the number of UUIDs can exceed 100. A single missed reference can silently break a login flow instead of failing loudly at import time, leaving administrators unaware until users start reporting issues.
keycloak-realm-clone automates the rewrite
The lightweight Node.js CLI keycloak-realm-clone handles the UUID remapping automatically. Run it without installing anything:
npx keycloak-realm-clone realm-export.json myrealm-dev
The tool reads the export, generates a new file named myrealm-dev-realm-export.json, and prints a summary of all changes. Options include custom output paths, manual override of the source realm name, and a dry-run mode for inspection before writing.
Under the hood, it rewrites every UUID-shaped value—role IDs, client IDs, user IDs, service-account references, protocol-mapper IDs, component IDs, and authentication-flow IDs—using a single old→new mapping table. That mapping guarantees that a role’s container reference, a client’s service-account link, and a flow’s execution chain remain intact after the rewrite.
Why it matters
For teams that spin up multiple environments from the same realm, this tool removes hours of manual editing and eliminates the risk of silent failures that can surface only after users are affected. It turns a brittle, one-off process into a repeatable automation step, making realm duplication on the same Keycloak instance both safe and practical.
Source: DEV Community. AI-assisted editorial synthesis — TechnoExpress.

