'how to get keycloak to export realm users and then exit

We run Keycloak docker image in AWS ECS and we need a way to export a realm and all users for automation purposes using ansible. We can run the following command with ansible to run the export

docker exec -i 702f2fd7858d \
  /bin/bash -c "export JDBC_PARAMS=?currentSchema=keycloak_service && 
  /opt/jboss/keycloak/bin/standalone.sh \
  -Djboss.socket.binding.port-offset=100 \
  -Dkeycloak.migration.action=export \
  -Dkeycloak.migration.provider=singleFile \
  -Dkeycloak.migration.realmName=API \
  -Dkeycloak.migration.usersExportStrategy=REALM_FILE \
  -Dkeycloak.migration.file=/tmp/my_realm.json"

but the docker container continues to run after the export. We cannot grep the logs looking for the export process finishing as we use an AWS Log Driver for Docker that prevents access to any logs. It's a pity that the Keycloak REST API does not support the inclusion of users in the existing partial-export endpoint or at least to have an endpoint that triggers the export of a realm including users into a mounted filed system.



Solution 1:[1]

I came up with this one-liner:

sh -c 'echo $$; exec /opt/jboss/keycloak/bin/standalone.sh -Djboss.socket.binding.port-offset=98 -Dkeycloak.migration.action=export -Dkeycloak.migration.provider=dir -Dkeycloak.migration.dir=/tmp/realms/' | { read pid; while read -r line; do echo "$line"; test "$line" = "${line% Export finished successfully}" || kill $pid; done; }

It does not have any timeout logic it just waits for Export finished successfully. It should be posix compatible.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 frederik-b