Files
infra-postgres/backup.sh
Matthieu THOLOT dce99f58d7
All checks were successful
Auto Tag / tag (push) Successful in 5s
feat : add Discord notifications to backup script
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 08:08:06 +00:00

67 lines
1.7 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
# Charger les variables d'environnement
source .env
BACKUP_DIR="./backups"
DATABASES=("sirh_prod" "inventory_prod" "lesstime_prod")
DATE=$(date +%Y-%m-%d_%H%M%S)
LOG_FILE="${BACKUP_DIR}/backup.log"
WEBHOOK_URL="${DISCORD_WEBHOOK_URL:-}"
mkdir -p "$BACKUP_DIR"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }
discord() {
local color="$1" title="$2" msg="$3"
[[ -z "$WEBHOOK_URL" ]] && return 0
curl -fsS -H "Content-Type: application/json" -d "{
\"embeds\": [{
\"title\": \"${title}\",
\"description\": \"${msg}\",
\"color\": ${color}
}]
}" "$WEBHOOK_URL" >/dev/null 2>&1 || true
}
fail() {
log "ERROR: $1"
discord 16711680 "Backup PostgreSQL - ECHEC" "$1"
exit 1
}
# Verifications
command -v docker &>/dev/null || fail "docker n'est pas installe"
# Supprimer les anciens backups (on ne garde que le dernier)
rm -f "${BACKUP_DIR}"/*.sql
log "Debut backup PostgreSQL"
DETAILS=""
ERRORS=0
for DB in "${DATABASES[@]}"; do
log "Dumping ${DB}..."
if docker compose exec -T postgres pg_dump -U admin "$DB" > "${BACKUP_DIR}/${DB}-${DATE}.sql" 2>/dev/null; then
SIZE=$(du -h "${BACKUP_DIR}/${DB}-${DATE}.sql" | cut -f1)
log "${DB} sauvegarde (${SIZE})"
DETAILS="${DETAILS}\\n- **${DB}** : ${SIZE}"
else
log "ERREUR sur ${DB}"
DETAILS="${DETAILS}\\n- **${DB}** : ERREUR"
((ERRORS++))
fi
done
if [[ $ERRORS -gt 0 ]]; then
fail "Backup termine avec ${ERRORS} erreur(s) :${DETAILS}"
fi
log "Backup termine avec succes"
discord 65280 "Backup PostgreSQL - OK" "Backup **${DATE}** termine\\n${DETAILS}"