Wednesday, September 1, 2021

How to automatically renew letsencrypt certficate

 Run the following line, which will add a cron job to /etc/crontab:


SLEEPTIME=$(awk 'BEGIN{srand(); print int(rand()*(3600+1))}'); echo "0 0,12 * * * root sleep $SLEEPTIME && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null


If you needed to stop your webserver to run Certbot, you’ll want to add pre and post hooks to stop and start your webserver automatically. For example, if your webserver is HAProxy, run the following commands to create the hook files in the appropriate directory:


sudo sh -c 'printf "#!/bin/sh\nservice haproxy stop\n" > /etc/letsencrypt/renewal-hooks/pre/haproxy.sh'

sudo sh -c 'printf "#!/bin/sh\nservice haproxy start\n" > /etc/letsencrypt/renewal-hooks/post/haproxy.sh'

sudo chmod 755 /etc/letsencrypt/renewal-hooks/pre/haproxy.sh

sudo chmod 755 /etc/letsencrypt/renewal-hooks/post/haproxy.sh


Congratulations, Certbot will now automatically renew your certificates in the background.


If you are interested in learning more about how Certbot renews your certificates, see the Renewing certificates section above.