#!/bin/bash # SSL Certificate Renewal Notification Script # Generated by Ansible set -e DOMAIN="{{ domain_name }}" EMAIL="{{ letsencrypt_email }}" LOG_FILE="/var/log/ssl-renewal.log" WEBHOOK_URL="{{ slack_webhook_url | default('') }}" # Log function log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE" } # Function to send notification send_notification() { local status="$1" local message="$2" if [[ -n "$WEBHOOK_URL" ]]; then curl -X POST -H 'Content-type: application/json' \ --data "{\"text\":\"SSL Renewal $status for $DOMAIN: $message\"}" \ "$WEBHOOK_URL" || true fi # Send email if available if command -v mail >/dev/null 2>&1; then echo "$message" | mail -s "SSL Renewal $status - $DOMAIN" "$EMAIL" || true fi } log "Starting SSL certificate renewal check for $DOMAIN" # Check certificate expiry EXPIRY_DATE=$(openssl x509 -in {{ ssl_certificate_path }} -noout -enddate 2>/dev/null | cut -d= -f2) EXPIRY_EPOCH=$(date -d "$EXPIRY_DATE" +%s) CURRENT_EPOCH=$(date +%s) DAYS_UNTIL_EXPIRY=$(( (EXPIRY_EPOCH - CURRENT_EPOCH) / 86400 )) log "Certificate expires in $DAYS_UNTIL_EXPIRY days" # Run certbot renewal if certbot renew --quiet --no-self-upgrade; then NEW_EXPIRY_DATE=$(openssl x509 -in {{ ssl_certificate_path }} -noout -enddate 2>/dev/null | cut -d= -f2) NEW_EXPIRY_EPOCH=$(date -d "$NEW_EXPIRY_DATE" +%s) NEW_DAYS_UNTIL_EXPIRY=$(( (NEW_EXPIRY_EPOCH - CURRENT_EPOCH) / 86400 )) if [[ $NEW_DAYS_UNTIL_EXPIRY -gt $DAYS_UNTIL_EXPIRY ]]; then log "Certificate renewed successfully. New expiry: $NEW_EXPIRY_DATE" send_notification "SUCCESS" "Certificate renewed successfully. Valid until $NEW_EXPIRY_DATE" # Reload Nginx if systemctl reload nginx; then log "Nginx reloaded successfully" else log "ERROR: Failed to reload Nginx" send_notification "WARNING" "Certificate renewed but Nginx reload failed" fi else log "Certificate was not renewed (not due for renewal)" fi else log "ERROR: Certificate renewal failed" send_notification "FAILED" "Certificate renewal failed. Please check server logs." exit 1 fi log "SSL renewal check completed"