Script 06 · Database

6. Install PostgreSQL (Smart Installer)

Installs PostgreSQL from the official PGDG repository and interactively creates a database user and database.

Category: Database Risk: Medium Lines: calculating Language: Bash / Linux
Back to index

What this script does

  • Install a selected PostgreSQL major version.
  • Create initial DB credentials and database ownership.
  • Avoid duplicate role/database creation where possible.

Prerequisites

  • Root access
  • Internet access to apt.postgresql.org
  • Clear PostgreSQL version choice

Execution flow

  1. Installs repo signing key
  2. Adds PGDG repository
  3. Installs selected PostgreSQL version
  4. Creates or updates DB role
  5. Creates or claims database

Validation checklist

  • systemctl status postgresql
  • psql --version
  • sudo -u postgres psql -l

Operational cautions

  • Storing entered passwords in shell history is avoided, but SQL command exposure should still be considered.
  • Firewall and pg_hba still need production hardening.

Original script notes

ℹ️ Script Info: A smart interactive installer that adds the official PostgreSQL repository, lets you choose the database version, and interacts with you to safely create initial users and databases.

Script source
cat << 'EOF' > install_pg_smart.sh && chmod +x install_pg_smart.sh && ./install_pg_smart.sh
#!/bin/bash
GREEN='\033[0;32m'; RED='\033[0;31m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'

clear
echo -e "${BLUE}=== PostgreSQL Smart Installer ===${NC}"

# --- 1. Setup Repository & Install ---
echo -e "${YELLOW}[*] Setting up Repo & Dependencies...${NC}"
sudo apt install -y curl ca-certificates
sudo install -d /usr/share/postgresql-common/pgdg
sudo curl -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc --fail https://www.postgresql.org/media/keys/ACCC4CF8.asc || { echo -e "${RED}Failed to download key${NC}"; exit 1; }
. /etc/os-release
sudo sh -c "echo 'deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $VERSION_CODENAME-pgdg main' > /etc/apt/sources.list.d/pgdg.list"
sudo apt update -y

echo -e "\n${BLUE}CHOOSE POSTGRESQL VERSION:${NC}"
echo "1) v17 (Latest)  2) v16  3) v15  4) v14"
read -p "Choice (1-4): " PG_OPT
case $PG_OPT in 1) V="17";; 2) V="16";; 3) V="15";; 4) V="14";; *) echo "Invalid"; exit 1;; esac

echo -e "${YELLOW}[*] Installing PostgreSQL $V...${NC}"
sudo apt install -y postgresql-$V postgresql-client-$V || exit 1
sudo systemctl start postgresql

# --- 2. User Configuration (Smart Check) ---
echo -e "\n${BLUE}USER CONFIGURATION:${NC}"
echo "1) Create New User"
echo "2) Use Default (postgres)"
read -p "Choice: " U_OPT

if [ "$U_OPT" == "1" ]; then
    while true; do
        read -p "Enter New Username: " NEW_U
        # Check if user already exists in postgres
        if sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='$NEW_U'" | grep -q 1; then
            echo -e "${RED}[!] User '$NEW_U' ALREADY EXISTS. Please use a different name.${NC}"
        else
            break
        fi
    done
    
    read -s -p "New User Password: " NEW_P; echo ""
    sudo -u postgres createuser "$NEW_U" 2>/dev/null
    sudo -u postgres psql -c "ALTER USER \"$NEW_U\" WITH PASSWORD '$NEW_P';" >/dev/null
    OWNER="$NEW_U"
    echo -e "${GREEN}[OK] User '$NEW_U' created successfully.${NC}"

elif [ "$U_OPT" == "2" ]; then
    OWNER="postgres"
    read -s -p "Set Password for user 'postgres': " PG_P; echo ""
    sudo -u postgres psql -c "ALTER USER postgres WITH PASSWORD '$PG_P';" >/dev/null
else 
    echo "Invalid Choice"; exit 1
fi

# --- 3. Database Configuration (Smart Check) ---
echo -e "\n${BLUE}DATABASE:${NC}"
while true; do
    read -p "Enter Database Name: " DB_N
    
    # Check if DB already exists
    if sudo -u postgres psql -lqt | cut -d \| -f 1 | grep -qw "$DB_N"; then
        echo -e "${YELLOW}[!] Database '$DB_N' ALREADY EXISTS.${NC}"
        echo "    Choose action:"
        echo "    1) Enter a different database name"
        echo "    2) Use DB '$DB_N' & set '$OWNER' as owner"
        read -p "    Choice (1/2): " DB_EXIST_ACT
        
        if [ "$DB_EXIST_ACT" == "2" ]; then
            echo -e "${YELLOW}[*] Changing owner of '$DB_N' to '$OWNER'...${NC}"
            sudo -u postgres psql -c "ALTER DATABASE \"$DB_N\" OWNER TO \"$OWNER\";"
            if [ $? -eq 0 ]; then
                echo -e "${GREEN}[OK] Owner permissions updated.${NC}"
                break
            else
                echo -e "${RED}[!] Failed to change owner.${NC}"
            fi
        fi
        # If 1 selected, loop will repeat and ask for new name
    else
        # If DB doesn't exist, create new
        echo -e "${YELLOW}[*] Creating database '$DB_N'...${NC}"
        if sudo -u postgres createdb -O "$OWNER" "$DB_N"; then
             echo -e "${GREEN}[OK] Database '$DB_N' created successfully with owner '$OWNER'.${NC}"
             break
        else
             echo -e "${RED}[!] Failed to create DB.${NC}"
             break
        fi
    fi
done

echo -e "\n${BLUE}=== INSTALLATION COMPLETE ===${NC}"
echo -e "Script saved at: $(pwd)/install_pg_smart.sh"
EOF
Done