Blog |Follow Nick on Mastodon| About
 

Last month I was very pleased that I had managed an automated Let's Encrypt certificate renewal; the other night the renewal broke as the certificate was issued from a different intermediate CA, so help others out I thought I'd share with you my cron script.

Before copy/pasting this script, you need to get started with tiny acme. I also recommend you read this post by Scott Heleme as it walks through the end-to-end process.

Once you're all setup, you can use something like the below script on a monthly basis (update paths for your environment and the email address):

#!/bin/bash
echo "----------------------"
echo "Start:" `date`

# Backup
cp -v /home/letsencrypt/priv/signed.crt /home/letsencrypt/priv/old/signed_$(date +%F).crt
cp -v /home/letsencrypt/priv/chained.pem /home/letsencrypt/priv/old/chained_$(date +%F).crt

# Renewal
python /home/letsencrypt/bin/letsencrypt_tiny.py --account-key /home/letsencrypt/priv/my.key --csr /home/letsencrypt/priv/my.csr --letsencrypt-dir /home/letsencrypt/challenges/ > /home/letsencrypt/priv/signed.crt 

# Find Issuer
ISSUER=`openssl x509 -noout -issuer -in /home/letsencrypt/priv/signed.crt | awk 'NF>1{print $NF}'`

echo "Certificate issued by $ISSUER"

case $ISSUER in
    X1)
        ISSUER_CERT="https://letsencrypt.org/certs/lets-encrypt-x1-cross-signed.pem"
        ;;
    X2)
        ISSUER_CERT="https://letsencrypt.org/certs/lets-encrypt-x2-cross-signed.pem"
        ;;
    X3)
        ISSUER_CERT="https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem"
        ;;
    X4)
        ISSUER_CERT="https://letsencrypt.org/certs/lets-encrypt-x4-cross-signed.pem"
        ;;
    *)
        echo -e "Undefined Intermediate CA - Please fix /home/letsencrypt/bin/letsencrypt.sh - Failed to match Intermediate CA $ISSUER not found" | mail -s "LE Renewal Error" "changeme_at_gmail_dot_com"
        echo "** Error: Failed to match Intermediate CA $ISSUER not found **"
        cp -v /home/letsencrypt/priv/old/chained_$(date +%F).crt /home/letsencrypt/priv/chained.pem
        exit
    ;;
esac

# Download Intermetdiate CA Cert
echo "Cert URL: $ISSUER_CERT"
wget -O - $ISSUER_CERT > /home/letsencrypt/priv/intermediate.pem

# Build Chain
cat /home/letsencrypt/priv/signed.crt /home/letsencrypt/priv/intermediate.pem > /home/letsencrypt/priv/chained.pem

# Restart nginx to install the cert
sudo service nginx reload
echo "End:" `date`

Things to note if the renewal breaks:

  1. It doesn't retry. Look at adding this smart renewal script to your daily cron: https://github.com/ScottHelme/Lets-Encrypt-Smart-Renew/
  2. It emails you and puts the old certificate chain back (then quits)

 

 
Nick Bettison ©