Files
notes-techniques/scripts/server-postgres/setup-postgres.sh

78 lines
2.6 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
# Basé sur un travail de Cédric Abonnel / Cédrix sous licence CC BY-NC 4.0
# Importer les fonctions communes
source "$(dirname "$0")/../common/common_utils.sh"
# Vérifier si le script est exécuté en root
check_root
set -e
echo "📦 Mise à jour des paquets..."
apt update -y
echo "📚 Installation de postgresql-common (pour script de dépôt officiel)..."
apt install -y postgresql-common
echo " Ajout automatique du dépôt officiel PostgreSQL (via pgdg script)..."
/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
echo ""
echo "🧩 Versions disponibles dans le dépôt :"
AVAILABLE_VERSIONS=$(apt-cache search "^postgresql-[0-9][0-9]$" | awk '{print $1}' | cut -d'-' -f2 | sort -nr)
echo "$AVAILABLE_VERSIONS"
read -p "➡️ Entrez la version PostgreSQL à installer (ex: 17) : " PG_VERSION
if ! echo "$AVAILABLE_VERSIONS" | grep -q "^${PG_VERSION}$"; then
echo "❌ Version PostgreSQL invalide ou non disponible : ${PG_VERSION}"
exit 1
fi
echo "📦 Installation de PostgreSQL $PG_VERSION..."
apt update -y
apt install -y "postgresql-${PG_VERSION}"
echo "🚀 Activation et démarrage du service PostgreSQL..."
systemctl enable postgresql
systemctl start postgresql
echo "⏳ Attente du démarrage du service PostgreSQL..."
sleep 3
echo "✅ Vérification du service..."
if ! systemctl is-active --quiet postgresql; then
echo "❌ Le service PostgreSQL ne fonctionne pas correctement."
journalctl -xeu postgresql --no-pager | tail -n 20
exit 1
fi
echo "🧪 Test de connexion à PostgreSQL..."
if ! sudo -u postgres psql -c '\q' 2>/dev/null; then
echo "❌ Échec de la connexion à PostgreSQL. Vérifiez que le socket est disponible."
echo " Astuce : systemctl status postgresql"
exit 1
fi
echo "🔐 Génération d'un mot de passe fort pour l'utilisateur postgres..."
POSTGRES_PASSWORD=$(generate_token 20)
echo "🔧 Configuration du mot de passe de l'utilisateur postgres..."
sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '${POSTGRES_PASSWORD}';"
echo "🔧 Configuration de l'accès local en md5..."
PG_HBA="/etc/postgresql/${PG_VERSION}/main/pg_hba.conf"
sed -i "s/^\(local\s\+all\s\+postgres\s\+\)peer/\1md5/" "$PG_HBA"
echo "♻️ Redémarrage de PostgreSQL pour appliquer les changements..."
systemctl restart postgresql
echo ""
echo "✅ Installation de PostgreSQL ${PG_VERSION} terminée."
echo "-------------------------------------------"
echo " Mot de passe de l'utilisateur postgres :"
echo " ${POSTGRES_PASSWORD}"
echo "-------------------------------------------"
echo " Pensez à le sauvegarder en lieu sûr."