Main admin account can't be recreated using env variable if it was previously deleted

I’m currently getting an error using keycloak 18 with a docker container.

2022-05-13 11:55:02,998 ERROR [org.keycloak.services] (main) KC-SERVICES0010: Failed to add user 'user' to realm 'master': user with username exists

I’m currently testing the upgrade from 16 to 18, my script works well on 16 but does not seem to be working for 18 but i can’t seem to find the reason why.

My script works well from afresh install, at the end of the script i delete the main “admin” account for security reason (i created other individual admin account).

2022-05-13 11:53:22 (UTC) | ACTION | executing: /opt/keycloak/bin/kcadm.sh delete users/<admin id> -r master

The above does the job properly and deletes the main admin account, if i connect to the DB, i can see that the main user is not found in the “user_entity” table.

The problem is on a second restart.

I get the error:

2022-05-13 11:55:02,998 ERROR [org.keycloak.services] (main) KC-SERVICES0010: Failed to add user 'user' to realm 'master': user with username exists

That’s whats bothering me, the startup script contains the admin credentials environment variable
KEYCLOAK_ADMIN and KEYCLOAK_ADMIN_PASSWORD so the user is picked up but it’s not being created even though its not in the table.

The keycloak 18 expected overall flow, and the keycloak 16 actual flow is the following:

  1. The startup script creates the admin account from env variable

  2. My custom configuration script does some work then deletes the admin account

  3. The container restarts

  4. The startup script creates the admin account from env variable

  5. My custom configuration script does some work then deletes the admin account

and so on

But the keycloak 18 actual flow is the following:

  1. The startup script creates the admin account from env variable

  2. My custom configuration script does some work then deletes the admin account

  3. The container restarts

  4. The startup script does not create the admin account from env variable

  5. My custom configuration script does not work since it can’t connect to the cli since the admin account was not recreated

I found out that if you already have users in the master realm, the admin user that you configured with the KEYCLOAK_ADMIN variable will not be created. I checked the keycloak code on github:

if (session.users().getUsersCount(realm) > 0) {
    throw new IllegalStateException("Can't create initial user as users already exists");
}

The above is the reason why the account does not created.
Out of curiosity, i deleted the other user accounts i had in the master realm and then it worked, the admin account got created.