#!/bin/bash # Configuration # Set to 'nginx' or 'apache2' depending on your web server WEB_SERVER_SERVICE="nginx" LOG_FILE="/var/log/certbot_renewal.log" # Ensure certbot is installed and available if ! command -v certbot &> /dev/null then echo "Certbot could not be found. Please install it first." | tee -a "$LOG_FILE" exit 1 fi echo "$(date) - Starting Let's Encrypt certificate renewal..." | tee -a "$LOG_FILE" # Run certbot renewal dry run first for testing echo "$(date) - Running certbot dry run..." | tee -a "$LOG_FILE" sudo certbot renew --dry-run --non-interactive --post-hook "sudo systemctl reload $WEB_SERVER_SERVICE" >> "$LOG_FILE" 2>&1 DRY_RUN_STATUS=$? if [ $DRY_RUN_STATUS -ne 0 ]; then echo "$(date) - Certbot dry run failed. Check log file for details." | tee -a "$LOG_FILE" exit 1 fi # Run actual certbot renewal echo "$(date) - Running actual certbot renewal..." | tee -a "$LOG_FILE" sudo certbot renew --non-interactive --post-hook "sudo systemctl reload $WEB_SERVER_SERVICE" >> "$LOG_FILE" 2>&1 RENEWAL_STATUS=$? if [ $RENEWAL_STATUS -eq 0 ]; then echo "$(date) - Certificate renewal successful and $WEB_SERVER_SERVICE reloaded." | tee -a "$LOG_FILE" elif [ $RENEWAL_STATUS -eq 1 ]; then echo "$(date) - Certificate renewal completed, but with errors. Check log for details." | tee -a "$LOG_FILE" else echo "$(date) - No certificates were due for renewal or an unexpected error occurred." | tee -a "$LOG_FILE" fi exit 0