Create a file in which we will be writing the script
nano /var/www/scripts/ssl-renew.sh
Script Content
#!/bin/bash
# Path to the Certbot executable
CERTBOT="/usr/bin/certbot"
# Email address to use for renewal notifications
EMAIL="email@example.com"
# Number of days before certificate expiry to trigger renewal
RENEWAL_THRESHOLD=30
# Function to check certificate expiry
check_certificate_expiry() {
echo "Checking SSL certificate expiry..."
expiry_date=$(openssl x509 -enddate -noout -in /etc/letsencrypt/live/mydomain.example.com/fullchain.pem | cut -d "=" -f 2)
expiry_epoch=$(date -d "$expiry_date" +%s)
current_epoch=$(date +%s)
days_remaining=$(( ($expiry_epoch - $current_epoch) / 86400 ))
echo "Days remaining until certificate expiry: $days_remaining"
}
# Function to renew certificate if expiry threshold is reached
renew_certificate() {
echo "Renewing SSL certificate..."
$CERTBOT renew --non-interactive --agree-tos --email $EMAIL
echo "Certificate renewed successfully."
# Add PM2 service restart commands here
echo "Restarting PM2 service..."
export PATH=/usr/local/bin:/usr/bin:/bin
export NODE_ENV=production
cd /var/www/node/nodeApp/
pm2 stop bin/www --name nodeApp >> /var/log/pm2.log 2>&1
pm2 start bin/www --name nodeApp >> /var/log/pm2.log 2>&1
pm2 save
echo "PM2 service restarted successfully."
}
# Main function
main() {
check_certificate_expiry
if [ "$days_remaining" -lt "$RENEWAL_THRESHOLD" ]; then
systemctl stop iptables
renew_certificate
systemctl start iptables
else
echo "Certificate renewal not required at this time."
fi
}
# Execute main function
main
Allow permission for the execution
chmod 777 /var/www/scripts/ssl-renew.sh
Write cronjob for renewal
sudo crontab -e
Add the content to the end of the file
#ssl renew script which will run daily at 23:59 to check ssl expiration days and if it is less than 30 days so it will renew certificate itself.
59 23 * * * /var/www/scripts/ssl-renew.sh >> /var/www/scripts/log_sslrenew-log.txt 2>&1