Why Monitor SSL Certificates?
Expired SSL certificates cause browser warnings, break API integrations, and erode user trust. Automated monitoring ensures you are alerted well before any certificate expires, giving you time to renew without service interruption.
Method 1: Shell Script with Cron
Create a script at /usr/local/bin/check-ssl.sh:
#!/bin/bash
DOMAINS="yourdomain.com api.yourdomain.com"
WARN_DAYS=14
for DOMAIN in $DOMAINS; do
EXPIRY=$(echo | openssl s_client -servername "$DOMAIN" -connect "$DOMAIN":443 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2)
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s)
NOW_EPOCH=$(date +%s)
DAYS_LEFT=$(( (EXPIRY_EPOCH - NOW_EPOCH) / 86400 ))
if [ "$DAYS_LEFT" -lt "$WARN_DAYS" ]; then
echo "WARNING: $DOMAIN SSL expires in $DAYS_LEFT days" | mail -s "SSL Expiry Alert: $DOMAIN" admin@yourdomain.com
fi
done
chmod +x /usr/local/bin/check-ssl.sh
Schedule it with cron to run daily:
echo "0 9 * * * /usr/local/bin/check-ssl.sh" | sudo crontab -
Method 2: Prometheus Blackbox Exporter
The Blackbox Exporter probes endpoints and exposes SSL metrics to Prometheus:
sudo apt install prometheus-blackbox-exporter
Add a probe target in Prometheus to scrape the probe_ssl_earliest_cert_expiry metric. Create an alert rule that fires when the certificate expires within 14 days:
- alert: SSLCertExpiringSoon
expr: (probe_ssl_earliest_cert_expiry - time()) / 86400 < 14
for: 1h
labels:
severity: warning
annotations:
summary: "SSL cert for {{ $labels.instance }} expires in {{ $value | humanizeDuration }}"
Method 3: Certbot Renewal Hooks
If you use Let's Encrypt via Certbot, enable automatic renewal checks:
sudo certbot renew --dry-run
Certbot's systemd timer runs twice daily by default. Verify with systemctl list-timers | grep certbot.