Files
nginx-configs/deploy.sh
2025-06-24 21:02:20 +01:00

152 lines
5.6 KiB
Bash
Executable File

#!/bin/bash
# ==============================================================================
# NGINX CONFIG & SSL DEPLOYMENT SCRIPT (v5)
#
# This script securely copies NGINX configuration files, tests the config,
# reloads Nginx, and then automates running Certbot to issue SSL certificates
# for all domains found in the `sites-available` directory.
#
# INSTRUCTIONS:
# 1. Ensure Certbot is installed on the remote server.
# (e.g., `sudo apt install certbot python3-certbot-nginx`)
# 2. Update the CERTBOT_EMAIL variable below.
# 3. Make the script executable: chmod +x <script_name>.sh
# 4. Run the script: ./<script_name>.sh
# ==============================================================================
# --- Configuration ---
REMOTE_USER="ubuntu" # The user you SSH in with (e.g., ubuntu, ec2-user)
REMOTE_HOST="3.9.182.122" # The IP address or domain of your server
CERTBOT_EMAIL="your-email@example.com" # Email for Let's Encrypt account
# --- File & Path Definitions ---
KEY_FILE="~/repos/azeem-macbookair.pem"
SOURCE_NGINX_CONF="nginx.conf"
SOURCE_SITES_DIR="sites-available"
# Destination paths on the remote server
DEST_NGINX_PATH="/etc/nginx/"
DEST_SITES_PATH="/etc/nginx/sites-available/"
# Temporary directory on the remote server (relative to the user's home dir)
REMOTE_TEMP_DIR="nginx_deploy_temp"
# --- Script Logic ---
echo "🚀 Starting NGINX & SSL deployment to $REMOTE_HOST..."
echo "--------------------------------------------------------"
# Expand the tilde (~) in the key file path to an absolute path.
EVAL_KEY_FILE=$(eval echo "$KEY_FILE")
# --- Pre-flight Checks ---
if [ ! -f "$EVAL_KEY_FILE" ]; then
echo "❌ ERROR: SSH key not found at $EVAL_KEY_FILE"
exit 1
fi
if [ ! -f "$SOURCE_NGINX_CONF" ]; then
echo "❌ ERROR: Source file '$SOURCE_NGINX_CONF' not found."
exit 1
fi
if [ ! -d "$SOURCE_SITES_DIR" ]; then
echo "❌ ERROR: Source directory '$SOURCE_SITES_DIR' not found."
exit 1
fi
# --- Local Operations: Find all unique domains ---
echo "-> Scanning local 'sites-available' for unique domain names..."
# This robust command finds all 'server_name' entries, handles multiple domains
# per line, removes duplicates, and creates a clean, space-separated list.
ALL_DOMAINS=$(grep -r "server_name" "$SOURCE_SITES_DIR" | sed 's/.*server_name\s*//' | sed 's/;//' | xargs -n1 | sort -u | tr '\n' ' ' | sed 's/ *$//')
if [ -z "$ALL_DOMAINS" ]; then
echo "⚠️ WARNING: No domains found in 'sites-available' config files. Skipping Certbot step later."
else
echo " ✅ Found domains: $ALL_DOMAINS"
fi
echo
# --- Remote Operations ---
# Step 1: Create the temporary directory on the remote server.
echo "-> Creating temporary directory on remote server..."
ssh -i "$EVAL_KEY_FILE" "${REMOTE_USER}@${REMOTE_HOST}" "mkdir -p $REMOTE_TEMP_DIR"
if [ $? -ne 0 ]; then
echo "❌ ERROR: Failed to create temporary directory. Aborting."
exit 1
fi
echo " ✅ Remote temporary directory is ready."
echo
# Step 2: Transfer all files to the temporary directory.
echo "- Transferring configuration files to temporary location..."
scp -i "$EVAL_KEY_FILE" -r "$SOURCE_NGINX_CONF" "$SOURCE_SITES_DIR" "${REMOTE_USER}@${REMOTE_HOST}:${REMOTE_TEMP_DIR}/"
if [ $? -ne 0 ]; then
echo "❌ ERROR: File transfer failed. Aborting."
exit 1
fi
echo " ✅ All files successfully transferred to temporary location."
echo
# Step 3: Move files into place, clean up, and test config.
echo "- Moving files into place with sudo and cleaning up..."
ssh -i "$EVAL_KEY_FILE" "${REMOTE_USER}@${REMOTE_HOST}" << EOF
# Move the main config file
sudo mv "$REMOTE_TEMP_DIR/nginx.conf" "${DEST_NGINX_PATH}nginx.conf"
# Move the sites-available files
sudo mv "$REMOTE_TEMP_DIR/sites-available/"* "$DEST_SITES_PATH"
# Remove the temporary directory
rm -rf "$REMOTE_TEMP_DIR"
echo " -> Verifying Nginx configuration..."
# Test the Nginx configuration for syntax errors
sudo nginx -t
EOF
if [ $? -ne 0 ]; then
echo "⚠️ WARNING: An error occurred on the remote server during the move or config test."
echo "You may need to log in manually to fix it: ssh -i $EVAL_KEY_FILE ${REMOTE_USER}@${REMOTE_HOST}"
exit 1
fi
echo " ✅ Files moved and configuration test passed."
echo
# Step 4: Reload Nginx to apply new configs before running Certbot
echo "- Reloading Nginx to apply new configurations..."
ssh -i "$EVAL_KEY_FILE" "${REMOTE_USER}@${REMOTE_HOST}" "sudo systemctl reload nginx"
if [ $? -ne 0 ]; then
echo "⚠️ WARNING: Nginx reload failed. Check the server status."
else
echo " ✅ Nginx reloaded successfully."
fi
echo
# Step 5: Ask to run Certbot if domains were found
if [ -n "$ALL_DOMAINS" ]; then
read -p "Run Certbot for the discovered domains? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
# Format domains for the certbot command (-d domain1 -d domain2 etc.)
CERTBOT_DOMAINS=$(echo "$ALL_DOMAINS" | sed 's/ / -d /g' | sed 's/^/-d /')
echo "- Running Certbot on the server. This may require interaction on the first run..."
ssh -t -i "$EVAL_KEY_FILE" "${REMOTE_USER}@${REMOTE_HOST}" \
"sudo certbot --nginx --non-interactive --agree-tos --email $CERTBOT_EMAIL --redirect $CERTBOT_DOMAINS"
if [ $? -eq 0 ]; then
echo " ✅ Certbot process completed."
else
echo "⚠️ WARNING: Certbot process finished with errors."
fi
fi
else
echo "-> Skipping Certbot step as no domains were found."
fi
# --- Completion ---
echo "--------------------------------------------------------"
echo "🎉 Deployment complete!"