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.

CRON Cheatsheet

I’m tired of always looking up CRON scheduling, so here it is including some examples.

CRON Scheduling table:

# ┌───────────── minute (0 - 59)
# │ ┌───────────── hour (0 - 23)
# │ │ ┌───────────── day of month (1 - 31)
# │ │ │ ┌───────────── month (1 - 12)
# │ │ │ │ ┌───────────── day of week (0 - 6)
# │ │ │ │ │                                      
# │ │ │ │ │
# │ │ │ │ │
# * * * * *  command to execute

Note that the day of week (0-6) typically starts with Sunday as the first index (0), so Monday = 1, Tuesday = 2 and so on. On some systems you might be able to also use 7 as Sunday.

CRON Examples:

Note that all the cron jobs output are redirected to /tmp/log.txt. If omitted, the default is to send an email to the sysadmin email address (if configured).

Run Python script every night at 02 am

* 02 * * * python /path/to/script.py >> /tmp/log.txt 2>&1

Run PHP script once every two hours

0 */2 * * * php /path/to/script.php >> /tmp/log.txt 2>&1

Run shell script every 10 minutes

*/10 * * * * /path/to/script.sh >> /tmp/log.txt 2>&1

Workaround for running a script every 15 seconds

* * * * * /path/to/script.sh >> /tmp/log.txt 2>&1

* * * * * sleep 15; /path/to/script.sh >> /tmp/log.txt 2>&1

* * * * * sleep 30; /path/to/script.sh >> /tmp/log.txt 2>&1

* * * * * sleep 45; /path/to/script.sh >> /tmp/log.txt 2>&1

Run a script every weekday at midnight

0 0 * * 1-5 /path/to/script.sh >> /tmp/log.txt 2>&1

Run script every Monday in June, July and August at 0530

30 05 * 6-8 1 /path/to/script.sh >> /tmp/log.txt 2>&1

Related post:

Linux Cheatsheet