Created
May 27, 2023 05:16
-
-
Save SafeEval/e01f015ccf716e82cc5d3ea6749f81a9 to your computer and use it in GitHub Desktop.
Export a Keycloak realm to JSON files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# https://stackoverflow.com/questions/65200310/export-users-and-roles-from-keycloak | |
# define the variables: url, credentials to access REST API, and the realm to export | |
KEYCLOAK_URL="http://keycloak.localhost" | |
KEYCLOAK_REALM="master" | |
KEYCLOAK_ADMIN="admin" | |
KEYCLOAK_ADMIN_PASSWORD="password" | |
REALM_NAME="demo" | |
# obtain the access token | |
ACCESS_TOKEN=$(curl -X POST "${KEYCLOAK_URL}/realms/${KEYCLOAK_REALM}/protocol/openid-connect/token" \ | |
-H "Content-Type: application/x-www-form-urlencoded" \ | |
-d "username=${KEYCLOAK_ADMIN}" \ | |
-d "password=${KEYCLOAK_ADMIN_PASSWORD}" \ | |
-d "grant_type=password" \ | |
-d 'client_id=admin-cli' \ | |
| jq -r '.access_token') | |
# export the realm as JSON | |
curl -X GET "${KEYCLOAK_URL}/admin/realms/${REALM_NAME}" \ | |
-H "Accept: application/json" \ | |
-H "Authorization: Bearer ${ACCESS_TOKEN}" \ | |
> keycloak_${REALM_NAME}_realm.json | |
# export the users | |
curl -X GET "${KEYCLOAK_URL}/admin/realms/${REALM_NAME}/users" \ | |
-H "Accept: application/json" \ | |
-H "Authorization: Bearer ${ACCESS_TOKEN}" \ | |
> keycloak_${REALM_NAME}_users.json | |
# export the roles | |
curl -X GET "${KEYCLOAK_URL}/admin/realms/${REALM_NAME}/roles" \ | |
-H "Accept: application/json" \ | |
-H "Authorization: Bearer ${ACCESS_TOKEN}" \ | |
> keycloak_${REALM_NAME}_roles.json | |
# integrate all 3 using jq's slurp | |
jq -s '.[0] + {users:.[1], roles:.[2]}' \ | |
"keycloak_${REALM_NAME}_realm.json" \ | |
"keycloak_${REALM_NAME}_users.json" \ | |
"keycloak_${REALM_NAME}_roles.json" \ | |
> keycloak_${REALM_NAME}_realm-incl-users-roles.json |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment