Skip to content

Instantly share code, notes, and snippets.

@michaelknurr
Last active August 28, 2024 11:35
Show Gist options
  • Select an option

  • Save michaelknurr/a8f1941c6f40c0d784b1e467fbc694ba to your computer and use it in GitHub Desktop.

Select an option

Save michaelknurr/a8f1941c6f40c0d784b1e467fbc694ba to your computer and use it in GitHub Desktop.
Shell script for automatted keycloak backups
#!/bin/bash
# check, if another export is currently running
if [ `ps -ef|grep "keycloak.migration.action=export" |grep -v grep |wc -l` != 0 ] ; then
echo "Another export is currently running";
exit 1;
fi
# try to extract keycloak home from running keycloak instance
KEYCLOAK_HOME=$(ps -ef|grep -v grep|grep jboss.home.dir|grep keycloak|sed 's/.*\(jboss.home.dir=\)//'|awk '{print $1}')
# if this did not work, try to set other location
if [ ! -x $KEYCLOAK_HOME ] ; then
KEYCLOAK_HOME=/opt/keycloak
fi
KEYCLOAK_BACKUP_DIR=$HOME/keycloak-backup
LOGFILE=/tmp/kc-$$.log
rm -rf $KEYCLOAK_BACKUP_DIR
$KEYCLOAK_HOME/bin/standalone.sh -Dkeycloak.migration.action=export -Dkeycloak.migration.provider=dir -Dkeycloak.migration.dir=$KEYCLOAK_BACKUP_DIR -Dkeycloak.migration.usersPerFile=500 -Djboss.socket.binding.port-offset=99 -Djboss.as.management.blocking.timeout=900 > $LOGFILE &
sleep 5
KEYCLOAK_PID=$(ps -ef|grep java|grep "keycloak.migration.dir="|awk '{print $2}')
SUCCESS="Export finished successfully"
FAILURE="seconds waiting for service container stability. Operation will roll back"
echo "Vorher: KEYCLOAK_PID=$KEYCLOAK_PID"
while [ `grep "$SUCCESS" $LOGFILE | wc -l` == 0 ] ; do
sleep 60
if [ `grep "$FAILURE" $LOGFILE | wc -l` != 0 ] ; then echo "killing keycloak with pid=$KEYCLOAK_PID"; kill $KEYCLOAK_PID; exit 1; fi;
done
kill $KEYCLOAK_PID
# delete all files that have been modified more than 30 days ago
find ~/archive/export -type f -mtime +30 -delete
tar cfz ~/archive/export/keycloak-backup-$(date +%Y-%m-%d).tar.gz --remove-files -C $HOME keycloak-backup/*
@sudmed
Copy link

sudmed commented Aug 28, 2024

Hi @michaelknurr
If the script is running while the main keycloak process runs, this error always occurs:

ERROR [org.jboss.as.controller.management-operation] (Controller Boot Thread) WFLYCTL0348: Timeout after [900] seconds waiting for service container stability. Operation will roll back.

Is this the expected behavior?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment