Spacebear Blog

Monitor and alert when TLS certificates expire

Published: September 10, 2020

If you can’t use a tool like Caddy that manages SSL/TLS certificate renewal, there are a few ways you can monitor your certificates to be alerted when they are close to expiring.

If you are using a Letsencrypt certificate then you should have this renew on a schedule using a cronjob so you can “set it and forget it”, although you may want to use some of the monitoring from below in case the renewal fails for whatever reason (perhaps a renewal ratelimit was reached).

The first way you could monitor certificate expiry is to add a script to your crontab that will check expiry each night, and alert you if the certificate expires within a certain pre-defined period. The pre-defined period would likely be however long it takes you to renew a certificate plus a few days buffer.

An example in your crontab might look like where at 05:00 your checks would be run and the script takes an argument that is the domain the script needs to check, and if the scripts fail, then an email to the address defined in the MAILTO environment variable will be sent.

00 5 * * * spacebear sh /opt/
00 5 * * * spacebear sh /opt/

The script that cron runs could look like


# Domain defined from argument
# 15 days in seconds
openssl x509 -checkend ${EXPIREAMOUNT} -noout -in <(openssl s_client -showcerts -connect ${DOMAIN}:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -ne 0 ]; then
  # email content will contain below warning. If you update the time above, you will want to update warning text
  echo "${DOMAIN} will expire within 15 days"
  exit 1

Another way would be to use a Sensu plugin, as you may already be using Sensu to monitor other assets. Assuming you are using Sensu Go, to add the plugin you need run sensuctl asset add sensu-plugins/sensu-plugins-http. Then use the following YAML to create a check that reviews the HTTPS endpoint every hour, and will warn 15 days before expiry and 4 days before expiry the alert level will change to critical.

type: CheckConfig
api_version: core/v2
  name: spacebear_ee_https_check
  namespace: default
  command: check-https-cert.rb -u -w 15 -c 4
  handlers: []
  interval: 3600
  publish: true
  - system

To add the YAML to sensu use the followinng command sensuctl create --file spacebear-ee-https-check.yaml

If you use Promethues you can follow this Prometheus Guide.