Keycloak – Export and Import a Realm

Learn to export an existing realm as a JSON file from the Keycloak server, and also to import a previously exported realm file with clients, policies and users. For demo purposes, we are using a Keycloak server instance running as a docker container.

1. Exporting a Realm

To export a realm, make sure it is already present in the Keycloak server. Begin the export process by launching the bash prompt for the docker container.

docker exec -it <container-id> bash

Next, run the /bin/ script to launch the export process. You can checkout all the export options and arguments for custom requirements.

The following command will export the realm name “howtodoinjava” including all the configured users in this realm. It will save the exported JSON file into the location ‘/opt/keycloak/data/import‘ with the name howtodoinjava-realm.json.

/opt/keycloak/bin/ export --dir /opt/keycloak/data/import --realm howtodoinjava --users realm_file

If required, we can copy and backup this realm file to a separate location as follows. The following command will copy the realm file into ‘c:/temp’ directory.

docker cp <container-id>:/opt/keycloak/data/import/howtodoinjava-realm.json c:/temp/howtodoinjava-realm.json

2. Importing a Realm

The best way to import a realm is using the user interface of a running Keycloak server instance. Login to the administrator console, and create a new realm with the same name as given in the realm file.

Additionally, select the “Resource file” as a previously exported realm file, as discussed in the previous section.

After we click the “Create” button, the realm will be created with all the clients, roles and users successfully.

If you face “Script upload is disabled” then you need to clean the realm file by removing the “authorizationSettings” from the JSON file as explained in this article.

3. Conclusion

In this short Keycloak tutorial, we learned to export a realm into JSON file, and then import a realm into Keycloak server. There are plenty of options for various usecases of importing and exporting realm which you can checkout in the official documentation.

Happy Learning !!

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.