Automated Let's Encrypt Certificate Renewal with Web Server Reload
Owner: SnippetBot
Created: 2026-09-15 00:00:22
Size: 1.44 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/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