Skip to content

Instantly share code, notes, and snippets.

@jcjones
Last active October 11, 2016 16:29
Show Gist options
  • Save jcjones/432eeaa6a2bf25e2c746 to your computer and use it in GitHub Desktop.
Save jcjones/432eeaa6a2bf25e2c746 to your computer and use it in GitHub Desktop.
Cron script to renew Let's Encrypt certs using the official client
#!/bin/bash
# This is free and unencumbered software released into the public domain.
#
# This script is designed to be run daily by cron. Please run it with randomness in its timing to
# avoid load spikes at Let's Encrypt. One example, running between midnight at 2 AM, would be:
#
# 0 0 * * * sleep $[(RANDOM % 115)+5]m ; /usr/sbin/letsencrypt-renew.sh
#
# If you aren't using Nginx, adjust the startServer and stopServer methods to suit. Also, you could
# use the webroot method.
FOUR_WEEKS=$((4*7*86400))
RENEW_LESS_THAN_SEC=${FOUR_WEEKS}
FIND=/usr/bin/find
SERVICE=/usr/sbin/service
OPENSSL=/usr/bin/openssl
LETSENCRYPT=/root/.local/share/letsencrypt/bin/letsencrypt
if [ ! -d /etc/letsencrypt/live ]; then
exit 1
fi
function stopServer {
if [ ${serverStopped} -eq 0 ] ; then
${SERVICE} nginx stop >/dev/null 2>&1
serverStopped=1
fi
}
function startServer {
${SERVICE} nginx start >/dev/null 2>&1
}
function issueCert {
domains=${1}
echo "Time to renew for domains ${domains}"
if ! ${LETSENCRYPT} certonly -tvv --keep ${domains} > /var/log/letsencrypt/renew.log 2>&1 ; then
echo Automated renewal failed:
cat /var/log/letsencrypt/renew.log
fi
}
function process {
cert=${1}
subject="$(${OPENSSL} x509 -noout -subject -in "${cert}" | grep -o -E 'CN=[^ ,]+' | tr -d 'CN=')"
subjectaltnames="$(${OPENSSL} x509 -noout -text -in "${cert}" | sed -n '/X509v3 Subject Alternative Name/{n;p}' | sed 's/\s//g' | tr -d 'DNS:' | sed 's/,/ /g')"
domains="-d ${subject}"
for name in ${subjectaltnames}; do
if [ "${name}" != "${subject}" ]; then
domains="${domains} -d ${name}"
fi
done
issueCert "${domains}"
exitcode=0
}
if [ $UID -ne 0 ] ; then
echo "Must be root"
exit 1
fi
trap startServer SIGINT SIGTERM SIGHUP
serverStopped=0
exitcode=1
for cert in $(${FIND} /etc/letsencrypt/live -name cert.pem); do
if ! ${OPENSSL} x509 -noout -checkend ${RENEW_LESS_THAN_SEC} -in "${cert}"; then
stopServer
process ${cert}
fi
done
startServer
exit ${exitcode}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment