今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

How to clone a Keycloak realm on the same instance (fixing "duplicate key value violates unique constraint")

Vimukthi Shohan Jayawardana 2026年07月11日 23:48 2 次阅读 来源:Dev.to

If you've ever tried to duplicate a Keycloak realm on the same server — say, to spin up a myrealm-dev realm alongside your existing myrealm — you've probably hit this wall: Export the realm from the Admin Console ( Realm settings → Action → Partial export , with clients and groups/roles included). Rename it in a text editor, or in the import dialog's "realm name" field. Import it back into the same Keycloak instance. Watch it fail with: ERROR: duplicate key value violates unique constraint "constraint_a" Detail: Key (id)=(51e1a26d-c24f-4454-9a34-708f1fc14917) already exists. Why this happens A realm export isn't just configuration — it's a snapshot of database rows. Every role, client, user, protocol mapper, component, and authentication flow in the export carries the same internal UUID it has in the live database. Renaming the realm field changes what the realm is called , but it does nothing to the dozens (often hundreds) of UUIDs referenced throughout the file. Import that JSON into the instance it came from, and Keycloak tries to insert rows whose primary keys already exist. Every single one collides. This is a known limitation, tracked upstream as keycloak/keycloak#24770 . Keycloak's exporter was never designed to produce an import-anywhere-including-here artifact — it assumes you're moving the realm to a different instance (dev → staging → prod), where the UUID space is independent. The manual fix (and why it doesn't scale) In principle you can fix this by hand: open the export JSON, find every UUID, and replace it with a fresh one, while keeping track of which old UUID maps to which new UUID so that references between objects (a role's containerId , a client's serviceAccountClientId , a flow's execution list) still point at the right thing after the rewrite. For a small realm with a handful of clients this is tedious but doable in an editor with careful find-and-replace. For a realm with custom roles, several clients, an identity provider, and a full set of a

本文内容来源于互联网,版权归原作者所有
查看原文