Skip to content

Instantly share code, notes, and snippets.

@haihoaes
Forked from michaelknurr/export-keycloak.sh
Created August 30, 2023 08:07
Show Gist options
  • Select an option

  • Save haihoaes/6d458793c99371114fa5519e4167546a to your computer and use it in GitHub Desktop.

Select an option

Save haihoaes/6d458793c99371114fa5519e4167546a 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/*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment