Skip to content
Snippets Groups Projects
Select Git revision
  • 2e46cef999de11ce4cb8e4648f68b49f33c0ff39
  • main default protected
2 results

backup_all_clients.sh

Blame
  • backup_all_clients.sh 2.30 KiB
    #!/bin/bash
    
    # === CONFIGURATION ===
    PG_VM_IP="10.42.170.2"
    BACKUP_VM_IP="10.42.170.3"
    SSH_KEY="$HOME/.ssh/cleSAE"
    PG_CONTAINER="postgres_container"
    PG_USER="odoo"
    PG_DUMP_DIR="/home/user/backup"
    REMOTE_BACKUP_DIR="/home/user/backup_postgres"
    TODAY=$(date +%Y-%m-%d)
    
    echo "Sauvegarde complète des bases PostgreSQL Odoo"
    
    # === Étape 1 : Installation rsync + sshpass sur les 2 VMs ===
    echo "Installation rsync et sshpass sur les VMs..."
    for VM in "$PG_VM_IP" "$BACKUP_VM_IP"; do
      ssh -i "$SSH_KEY" root@$VM "apt update -y && apt install -y rsync sshpass"
    done
    
    # === Étape 2: Configuration clé SSH entre VM PostgreSQL et VM Sauvegarde ===
    echo "Vérification clé SSH pour rsync (VM PostgreSQL ➜ VM Backup)..."
    ssh -i "$SSH_KEY" root@$PG_VM_IP bash <<EOSSH
    set -e
    apt install -y sshpass
    
    # Générer clé SSH si elle n'existe pas
    if [ ! -f /root/.ssh/id_rsa ]; then
      echo " Génération d'une nouvelle clé SSH..."
      ssh-keygen -t rsa -N "" -f /root/.ssh/id_rsa
    fi
    
    # Copier la clé vers la VM de sauvegarde
    echo "Copie de la clé publique dans backup-gp2"
    sshpass -p 'root' ssh-copy-id -o StrictHostKeyChecking=no -i /root/.ssh/id_rsa.pub root@$BACKUP_VM_IP
    EOSSH
    
    # === Étape 3 : Dump des bases client dans postgres-gp2 ===
    echo "Dump des bases client depuis postgres-gp2..."
    ssh -i "$SSH_KEY" root@$PG_VM_IP bash <<EOF
    set -e
    mkdir -p $PG_DUMP_DIR/$TODAY
    
    docker exec $PG_CONTAINER psql -U $PG_USER -t -c "SELECT datname FROM pg_database WHERE datname LIKE '%_db';" | while read dbname; do
      dbname=\$(echo \$dbname | xargs)
      if [[ ! -z "\$dbname" ]]; then
        echo "Dump de \$dbname..."
        docker exec $PG_CONTAINER pg_dump -U $PG_USER -d \$dbname > $PG_DUMP_DIR/$TODAY/\$dbname.sql
      fi
    done
    EOF
    
    # === Étape 4 : Rsync vers backup-gp2 ===
    echo "Transfert des dumps vers la VM de sauvegarde..."
    ssh -i "$SSH_KEY" root@$PG_VM_IP "rsync -az -e 'ssh -o StrictHostKeyChecking=no' $PG_DUMP_DIR/$TODAY/ root@$BACKUP_VM_IP:$REMOTE_BACKUP_DIR/$TODAY/"
    
    echo "Sauvegarde terminée : $TODAY transférée vers $BACKUP_VM_IP:$REMOTE_BACKUP_DIR"
    
    done
    EOF
    
    # === Étape 5 : transfert vers la VM de sauvegarde ===
    echo "Transfert des dumps vers la VM de sauvegarde..."
    ssh -i "$SSH_KEY" root@$PG_VM_IP "rsync -az $BACKUP_DIR/$TODAY root@$BACKUP_VM_IP:$REMOTE_BACKUP_DIR/"
    
    echo "✅ Sauvegarde complète envoyée à $BACKUP_VM_IP:$REMOTE_BACKUP_DIR/$TODAY"