Set up Certbot to automatically renew SSL certificates

Certbot is an excellent way to protect sites with an SSL certificate. But certificates only last for three months before needing to be renewed. So here is a way to configure your LAMP server to renew certificates automatically, and without needing to stop Apache to do so.

First get your installation up to date, and then install the plugin that integrates Certbot with Apache, to automate obtaining a certificate and configuring HTTPS within the web server:

sudo apt update
sudo apt install python3-certbot-apache

Then edit each of your virtual hosts for which you'd like to enable auto-renewal:

sudo vim /etc/letsencrypt/renewal/zenariosite.tribalforge.net.conf

To do all of them:

sudo vim /etc/letsencrypt/renewal/*

... and within vim you can type :wn to Write the file and move to the Next file.

Make sure each file contains, in its [renewalparams] section:

authenticator = apache
installer = apache

Remove any other line that specifies authenticator.

Check if this directory contains any files:

ls -la /etc/letsencrypt/renewal-hooks/deploy/

If not, then set Certbot to reload Apache after it has performed renewals, adding the reload instruction and making the script executable:

sudo vim /etc/letsencrypt/renewal-hooks/deploy/reload-apache.sh

Add this text inside the file:

#!/bin/bash
systemctl reload apache2

Make it executable:

sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/reload-apache.sh

Now see if the Certbot timer is active:

sudo systemctl status certbot.timer

If it's not enabled, enable it:

sudo systemctl enable certbot.timer
sudo systemctl start certbot.timer

Then test your setup:

sudo certbot renew --dry-run

This should show success messages for all domains, although if domains have incorrect DNS settings or other mis-configurations they will show errors.