Certificates renewal can be difficult to automate leading to errors that will mark the website as “Insecure”.
Before continue, ensure you haven’t the /etc/cron.d/certbot file launching:
If a crontab appear, you already have an automatic renew enabled via a certbot plugin like nginx or apache (the preferred method) and you shouldn’t do nothing.
The following will apply to standalone method, a small webserver provided by Let’s Encrypt that will listen the 80 port, without any existing auto-renew cron script. It’s very useful in cases where a plugin for your webserver is not available, like haproxy.
In this case, here’s how to automate certificate renewal with nginx as webserver:
sudo nano /etc/cron.d/certbot-custom
And then add to the crontab these lines pressing A to edit:
37 02 * * * root certbot -q renew --pre-hook="systemctl stop nginx" --post-hook="systemctl start nginx"
The root before certbot is the user who will run the command.
Every day at 02.37 the certificate will be asked for renewal in quiet mode to avoid to spam on root mailbox, especially useful if you use external SMTP server for system mails on Linux.
After you’ve typed these lines, type:
To write and quit. The /etc/cron.d/certbot-custom file will be easily accessible and maintainable compared to crontab -e, but it is a valid method too. If you use crontab -e, do it as root and do not add root after the last *.
To exactly mimic the certbot cron plugin, transform the line on /etc/cron.d/certbot-custom file to:
37 02 * * * root test -x /usr/bin/certbot -a \! -d /run/systemd/system && perl -e 'sleep int(rand(43200))' && certbot -q renew --pre-hook="systemctl stop nginx" --post-hook="systemctl start nginx"
Before run, all paths will be checked, and a random wait will be added. If your webserver requires additional commands, create a script to be executed in –post-hook.
Other Linux distributions
If you’re using a different Linux OS you can locate certbot-auto using the following command:
And then you can use it on the crontab.
You’ve also to use the alternative of systemctl for your system to refresh the certificates on the webserver.
If you’ve to do get your first certificate, here you can get more information about how to install free Let’s Encrypt certificates on nginx.
When auto-renew certificates
Since certificates lasts for about three months, you can tell crontab to run this every week instead every day accordingly.
Adding the 0 on the 5th position will tell crontab to run the command every Sunday at 2 AM (2nd position) and 37 minutes (1st position).
If you find this syntax difficult you can use crontab.guru to easily generate the crontab.
Updated on august 16th, 2019