Renew Let's Encrypt SSL cert with cron

This is an example of using the --renew-hook feature of certbot.  The renew hook script will only run If certbot actually creates updated certs.  Refer to https://certbot.eff.org/docs/install.html if certbot is not already installed.

File: /etc/cron.d/certbot

0 */12 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(3600))' 
 && certbot -q renew --authenticator=webroot --webroot-path=/var/www/html --renew-hook=/usr/local/sbin/certbot-renew-hook.sh

Notes: 

  1. The --authenticator and --webroot-path arguments are optional and force certbot to use the existing web server regardless of the authenticator type used when creating certificates.  This may be useful if the certificates were created with the certbot standalone http server and port 80 is no longer available because the production web server uses port 80.
  2. The --webroot-path location must contain sub directory .well-known and be writable for certbot when creating certificates.  It has to be accessible at http://{your-host}/.well-known so if the site has rules for forcing https or authentication you may need something like this in your /etc/nginx/sites-enabled/{your-site}
    server {
    	listen 80;
    	server_name {your-site};
    	root /var/www/html;
    
            location /.well-known {
                    allow all;
            }
    
            location / {
                    return 301 https://$host$request_uri;
            }
    }
    

Create the hook script that will restart anything using the certs 

For this example, it restarts nginx and a docker mailserver.

File: /usr/local/sbin/certbot-renew-hook.sh

#!/bin/bash

exec > /var/log/certbot-renew-hook.log
exec 2>&1 

set -x
date
nginx -t -q && nginx -s reload
MAIL_CONTAINER_UP=$(sudo docker inspect -f {{.State.Running}} mail)
if [ "$MAIL_CONTAINER_UP" == "true" ]
then
  docker exec mail service postfix reload
  docker exec mail service dovecot reload
fi
exit 0