#!/usr/bin/env bash # # docker-exec-cmd.sh set -o errexit set -o errtrace set -o nounset set -o pipefail TODAY_DATE=$(date "+%Y%m%d") echo ${TODAY_DATE} # If something goes wrong, this script does not run forever, but times out TIMEOUT_SECONDS=3600 # Logfile for the keycloak export instance LOGFILE=/opt/jboss/export/keycloak_backup_${TODAY_DATE}.sh.log # destionation export file JSON_EXPORT_FILE=/opt/jboss/export/realms-export-single-file.json KEYCLOAK_EXPORT_DIR=/opt/jboss/export/ KEYCLOAK_BACKUP_DIR=${KEYCLOAK_EXPORT_DIR}${TODAY_DATE}/ echo ${KEYCLOAK_BACKUP_DIR} KEYCLOAK_TAR=keycloak-backup-${TODAY_DATE}.tar.gz # Remove files from old backups inside the container # You could also move the files or change the name with timestamp prefix rm -f ${LOGFILE} ${JSON_EXPORT_FILE} if [ -f ${KEYCLOAK_EXPORT_DIR}${KEYCLOAK_TAR} ]; then echo "tar file exist." rm -f ${KEYCLOAK_EXPORT_DIR}${KEYCLOAK_TAR} fi if [ -d "$KEYCLOAK_BACKUP_DIR" ] then echo "$KEYCLOAK_BACKUP_DIR exist" rm -r ${KEYCLOAK_BACKUP_DIR} fi # Start a new keycloak instance with exporting options enabled. # Use the port offset argument to prevent port conflicts # with the "real" keycloak instance. timeout ${TIMEOUT_SECONDS}s \ /opt/jboss/keycloak/bin/standalone.sh \ -Djboss.socket.binding.port-offset=99 \ -Djboss.as.management.blocking.timeout=${TIMEOUT_SECONDS} \ -Dkeycloak.migration.action=export \ -Dkeycloak.migration.provider=dir \ -Dkeycloak.migration.dir=${KEYCLOAK_BACKUP_DIR} \ -Dkeycloak.migration.usersPerFile=1000 \ > ${LOGFILE} & #sudo docker exec -it sckeycloak /opt/jboss/keycloak/bin/standalone.sh -Djboss.socket.binding.port-offset=100 -Dkeycloak.migration.action=export -Dkeycloak.migration.realmName=AnalyticManagerV8 -Dkeycloak.migration.provider=dir -Dkeycloak.migration.usersPerFile=1000 # Grab the keycloak export instance process id PID="${!}" # Wait for the export to finish # It will wait till it sees the string, which indicates # a successful finished backup. # If it will take too long (>TIMEOUT_SECONDS), it will be stopped. timeout ${TIMEOUT_SECONDS}s \ grep -m 1 "Export finished successfully" <(tail -f ${LOGFILE}) # Stop the keycloak export instance kill ${PID} # delete all files that have been modified more than 30 days ago find ${KEYCLOAK_EXPORT_DIR} -type f -mtime +30 -delete # tar cfz ${KEYCLOAK_EXPORT_DIR}keycloak-backup-${TODAY_DATE}.tar.gz --remove-files -C $HOME ${KEYCLOAK_BACKUP_DIR}/* tar cfz ${KEYCLOAK_EXPORT_DIR}${KEYCLOAK_TAR} ${KEYCLOAK_BACKUP_DIR} && rm -R ${KEYCLOAK_BACKUP_DIR} if [ -f ${KEYCLOAK_EXPORT_DIR}${KEYCLOAK_TAR} ]; then echo "tar file exist, change file permission" chmod 777 ${KEYCLOAK_EXPORT_DIR}${KEYCLOAK_TAR} fi