Automating LetsEncrypt certificate renewal

LetEncrypt wants everyone to convert their old cleartext web servers over to HTTPS, so they give away free basic domain validation trusted certificates just to get everyone on the bandwagon (30M active certs so far!) and it’s supposed to be easy to renew, but my Apache instance was giving me trouble.

Turns out the way I have things configured with my cert and mail domain cert, the new key that’s created every 90 days has to be specified in the Apache configuration file. To help cert-bot accomplish this rotation, and provide some XML-formatted logging so I can neatly ingest things into MarkLogic, I wrote this script:

#!/bin/bash 


# XML output - start
echo "<report>"
startTime=`date +%Y-%m-%dT%H:%M:%S.%N%:z`
startTimeSeconds=`date -d $startTime +%s`
echo "  <dateTimeInitiated>$startTime</dateTimeInitiated>"
echo "  <jobOutput>"


apache2ctl stop

# Renew the certs
/root/certbot/certbot-auto renew

# Replace the Apache cert file with the most recent
KEYFILE=`ls -arth1 /etc/letsencrypt/keys/ | grep -v '^\..*' | tail -1`
rm /etc/letsencrypt/live/key-certbot.pem
ln -s "/etc/letsencrypt/keys/$KEYFILE" /etc/letsencrypt/live/key-certbot.pem

apache2ctl start


# XML output - end
echo "  </jobOutput>"
endTimeSeconds=`date +%s`
echo "  <jobDurationSeconds>`expr $endTimeSeconds - $startTimeSeconds`</jobDurationSeconds>"
echo "</report>"
autorenew.sh

Then, I have the system call this script at the start of every month. Or whatever interval makes sense. I used Crontab Generator to help, since my CRON-fu was rusty.

# m   h   dom mon dow   command
  4   21  1   *   *     /root/certbot/autorenew.sh >> /root/certbot/autorenew.txt 2>&1
crontab -e

Looks pretty in MarkLogic’s Query Console… ready for doing stuff with. Once I get a pile of them, I’ll make some bar charts.

Autorenewal logs as XML in MarkLogic Query Console

That’s all!

https://www.youtube.com/watch?v=Eh-FZcydhy0

 

masyukun Written by:

Software engineer consultant.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.