Useful Bash Scripts: Force Renew All Certificates With Certbot
bash certbot Linux

Useful Bash Scripts: Force Renew All Certificates With Certbot

Lucas Raymond Laprad
Lucas Raymond Laprad


I have a lot of scripts that sit on my public facing servers for various situations, and a couple times I've needed to manually force renew certificates. Instead of doing them manually with certbot or waiting for your chron job, here is a quick script that will force renew each domain found by certbot, and move them to /etc/ssl.

Remember to backup your certificates before using this script.



Script Assumptions & Things To Know

- You use certbot to handle your domain certificates and that it's already available on the system.
- Your certificates are deployed in the directory "/etc/ssl".
- The certificate will be concatenated and deployed into /etc/ssl and will be named based on your domain. For example, if you domain is "coolestwebsiteever.com", the certificate will use the full domain for the file name.

The Script

Create the file with nano, vim, micro, etc :

[root@server]: micro force-renew.sh

Paste the script into your editor then save the file :

#!/bin/bash
echo "Forcing renewal of all certificates..."
certbot_output=$(sudo certbot renew --force-renewal)
echo "$certbot_output"

# Check if certbot command was successful
certbot_exit_code=$?
if [ $certbot_exit_code -eq 0 ]; then
    echo "Certificate renewal successful."
else
    echo "Certificate renewal failed. Exiting script."
    exit 1
fi

# Combine fullchain.pem and privkey.pem files for each domain
echo "Concatenating certificates and creating new files..."

# Iterate over each domain directory in /etc/letsencrypt/live/
for domain_path in /etc/letsencrypt/live/*/; do
    domain=$(basename "$domain_path")

    # Concatenate fullchain.pem and privkey.pem files and redirect output to new file in /etc/ssl/ with the domain name
    cat_output=$(cat "/etc/letsencrypt/live/$domain/fullchain.pem" "/etc/letsencrypt/live/$domain/privkey.pem" > "/etc/ssl/$domain" 2>&1)
    cat_exit_code=$?
    if [ $cat_exit_code -eq 0 ]; then
        echo "Certificates for $domain were successfully concatenated."
    else
        echo "Failed to concatenate certificates for $domain."
        echo "Error message: $cat_output"
        exit 1
    fi
done

echo "All certificates have been concatenated and saved in /etc/ssl/."

Mark the new script as executable

[root@server]: chmod +x force-renew.sh


Depending on how many domains are being renewed, it may take a few moments for the script to give you any output. Once the renewal and deployment are complete, you will see the full output of which domains were renewed and any errors that occurred.

In the future, I will likely update this script to be more robust and have more output as the process completes.