Blog |Follow Nick on Twitter| 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):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/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)

rgds,

Nick

 
Nick Bettison ©