Flush/delete all users from a realm

Is there an easy way to remove all users from a realm, we have something like 30,000 users in our test realm that need to be cleared out - currently running a xargs process to clear out 10 at a time but that’s going to take hours.

Export realm without users, delete realm, import realm?

1 Like

That worked for me. Keep in mind that passwords and client secrets aren’t included in the export. For example, I had to re-enter my SMTP password, and re-generate client secrets, then update those client secrets in my application.

I don’t know how accurate this is anymore.
My realm export contains the client’s secrets but …
I saw that when you create a service account a user is also created for that account so you’ll probably need to keep those. But you could export everything and just remove all users from your export that are not of the type you want to keep.
So you can probably avoid the step to regenerate client secrets and replacing them everywhere.
I don’t know about the SMTP password if there is a solution for that one.

In case someone stumbles on that question, here is my solution using kcadm.sh:

kcadm=/opt/keycloak/bin/kcadm.sh
$kcadm config credentials --server http://localhost:8080/auth --realm master --user admin
for x in $($kcadm get users -r myrealm|jq -r '.[].id'); do $kcadm delete users/$x -r myrealm; done

Since this deletes one user at a time, it takes quite a while, but it’s okay for setups with a few hundred users.

1 Like