Purge unused realms

I have keycloak instance with over 2000 realms. There are many realms that are not in use (old, realms created for testing etc). Is there a mechanism to find these realms and delete them manually or automatically based on the last used time stamp or any other attribute. Any help on this would be much appreciated. Thank you in advance.

You can call the admin/realms endpoint and get a list of all realms.
Go over them and check against one of the properties you need.

The Keycloak REST API is not fully documented so it’s better to dive into the source code.
The keycloak-admin-client is the best resource in my opinion.
A couple of examples on how to use it Keycloak Admin Client in Spring Boot

You could just do the following based on the examples in the link I posted

RealmsResource realmsResource = keycloak.realms();
for (RealmRepresentation realmRepresentation : realmsResource.findAll()) {
    // Do your thing
}

Thanks @zonaut for your reply. I have used REST API for keycloak before but have not used Admin client. So have very less idea on getting started with it. I reffered the link you shared (Keycloak Admin Client in Spring Boot). I am quite sure of doing the things at the keycloak side as you mentioned in your examples but not the code part on from where to run.

If you don’t know Java you can try the nodejs alternative found in https://github.com/keycloak/keycloak-nodejs-admin-client, I’ve never used it so I don’t know how complete it is.

You can also look into the source code under https://github.com/keycloak/keycloak/tree/master/integration/admin-client/src/main/java/org/keycloak/admin/client/resource and see each available path that you could use.

realmsResource.findAll() = /admin/realms

Great @zonaut. Thanks much for your help :slight_smile:

Hi upendra, can you tell me how you managed to create 2000 realms in keycloak ? I use the version 11 and I am limited to nearly 400 realms.

Your answer could save my life :slight_smile:

Best regards,
Thibaud