BASH

Automate Let's Encrypt SSL Certificate Renewal

Discover how to create a simple bash script to automate the renewal of Let's Encrypt SSL certificates, ensuring your web applications remain secure and accessible.

#!/bin/bash

# Path to Certbot executable (adjust if needed)
CERTBOT_PATH="/usr/bin/certbot"

# Log file for renewals
LOG_FILE="/var/log/certbot_renew.log"

# Command to restart your web server after renewal (e.g., Nginx, Apache)
# NGINX: service nginx reload
# APACHE: service apache2 reload
RESTART_COMMAND="service nginx reload"

echo "--- Starting Certbot Renewal at $(date) ---" >> $LOG_FILE

# Run Certbot renewal with quiet output and hook to restart web server
$CERTBOT_PATH renew --quiet --post-hook "$RESTART_COMMAND" >> $LOG_FILE 2>&1

# Check the exit status of certbot
if [ $? -eq 0 ]; then
    echo "Certbot renewal successful." >> $LOG_FILE
else
    echo "Certbot renewal FAILED or no certificates needed renewal." >> $LOG_FILE
    exit 1
fi

echo "--- Finished Certbot Renewal at $(date) ---" >> $LOG_FILE
How it works: This script automates the process of renewing Let's Encrypt SSL certificates using `certbot`. It runs `certbot renew` with the `--quiet` flag to prevent interactive prompts and uses `--post-hook` to execute a command (like restarting Nginx or Apache) only if certificates were successfully renewed. All output is logged for review, ensuring web services remain secure without manual intervention. This is typically scheduled as a cron job.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs