CRON script to auto-renew SSL certificate and restart apache webserver using Certbot

Setting up a SSL certificate on a brand new server is so easy thanks to Certbot. But remember that every LetsEncrypt certificate expires after 3 months, so you better remember to renew it. Also, just renewing the certificate isn’t enough. Your apache webserver doesn’t know that it has been renewed, so you have to restart the webserver as well. Thankfully, certbot has a hook if the certificate has been renewed where we can add extra commands, such as restarting apache.

I like to put this in my crontab so I never have to think about it:

* 04 * * * sudo certbot renew --renew-hook "service apache2 restart" >> /home/user/logs/certbot.txt

Replace service apache2 restart with systemctl restart apache2 if you prefer to use systemctl syntax.

This will check the certificate every night at 0400 and renew it if necessary. If the certificate has been renewed, it will also restart apache.