infra-oasis21/backup_db.sh

62 lines
1.3 KiB
Bash
Raw Normal View History

2024-01-20 08:49:11 +01:00
#!/usr/bin/env bash
# usage: <script> <container-name> <database-type>
#
# exports the database of a running docker container in a dump in $BACKUP_DIR/$CONTAINER_NAME/
BACKUP_DIR=/DATA/BACKUP/dbdumps
# Check container existence
CONTAINER="$1"
if ! docker ps | grep -q "$CONTAINER"
then
echo "The container $CONTAINER doesn't exist or doesn't run"
exit 1
fi
# Check database type
TYPE="$2"
COMMAND=""
case "$TYPE" in
postgresql)
POSTGRES_USER=$(docker exec "$CONTAINER" env | grep POSTGRES_USER | cut -d= -f2)
COMMAND="pg_dumpall -c -U $POSTGRES_USER"
EXTENSION=sql
;;
mariadb)
MARIADB_USER=$(docker exec "$CONTAINER" env | grep MYSQL_USER | cut -d= -f2)
MARIADB_PASSWORD=$(docker exec "$CONTAINER" env | grep MYSQL_PASSWORD | cut -d= -f2)
COMMAND="mariadb-dump -u $MARIADB_USER --password=$MARIADB_PASSWORD --all-databases"
EXTENSION=sql
;;
mongodb)
COMMAND="mongodump --archive"
EXTENSION=mongodump
;;
ldap-config)
COMMAND="slapcat -n 0"
EXTENSION=config.ldif
;;
ldap-content)
COMMAND="slapcat -n 1"
EXTENSION=content.ldif
;;
*)
echo "I don't know $TYPE database type."
exit 1
esac
# Ensure directory exists
mkdir -p "$BACKUP_DIR/$CONTAINER"
# Export database
docker exec "$CONTAINER" $COMMAND > "$BACKUP_DIR/$CONTAINER/dump.$EXTENSION"
exit $?