bashintermediate

SSL Certificate Renewal with Certbot

Automate Let's Encrypt SSL certificate issuance and renewal with Certbot and NGINX reload.

bash
#!/usr/bin/env bash
set -euo pipefail

DOMAIN="example.com"
EMAIL="admin@example.com"

# Install certbot
sudo apt update && sudo apt install -y certbot python3-certbot-nginx

# Issue certificate (NGINX plugin handles validation + config)
sudo certbot --nginx -d "$DOMAIN" -d "www.$DOMAIN" \
  --non-interactive --agree-tos --email "$EMAIL" \
  --redirect  # auto-add HTTP→HTTPS redirect

# Check certificate
sudo certbot certificates

# Test renewal (dry run)
sudo certbot renew --dry-run

# Auto-renewal timer (certbot installs this automatically)
systemctl list-timers | grep certbot

# Manual renewal with NGINX reload hook
sudo certbot renew --deploy-hook 'systemctl reload nginx'

# Setup cron for renewal (if systemd timer not available)
# 0 3 * * * certbot renew --deploy-hook 'systemctl reload nginx' >> /var/log/certbot-renew.log 2>&1

# Check certificate expiry
openssl x509 -in /etc/letsencrypt/live/$DOMAIN/fullchain.pem -noout -dates

# Test SSL configuration
curl -vI "https://$DOMAIN" 2>&1 | grep -E '(SSL|subject|expire)'

Use Cases

  • Automated HTTPS setup for web servers
  • SSL certificate renewal without downtime
  • Let's Encrypt integration with NGINX

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.