DEV Community

Cover image for Let's Encrypt Certificate Auto-Renewal Script
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Let's Encrypt Certificate Auto-Renewal Script

This article was originally published on bmf-tech.com.

Overview

This post introduces a script for automatically renewing Let's Encrypt certificates. I had created it before, but due to various issues and changes in server environments, I couldn't leave a complete version, so I have summarized it again.

Environment

  • nginx v1.12.0

※ This post does not cover the installation of Let's Encrypt or how to execute shell scripts.

Script

This script renews the certificate once a month regardless of its expiration (--force-renew) and sends a Slack notification of the renewal result (success or failure).

The Slack configuration values are managed in an external file.

#!/bin/sh

# Import config
. /home/bmf/scripts/conf/slack.conf

# Stop Nginx
/usr/sbin/service nginx stop

# POST
if ! /home/bmf/certbot/certbot-auto renew --force-renew ; then
  sleep 15

  # Slack Title
  TITLE=${TITLE:-"Let's Encrypt更新エラー通知"}

  # Slack Message
  MESSAGE=${MESSAGE:-"証明書の更新に失敗しました。"}

  #POST
  curl -s -S -X POST --data-urlencode "payload={
                \"channel\": \"${SL_CH_LETSENCRYPT}\",
                \"username\": \"${SL_BOTNAME}\",
                \"attachments\": [{
                \"color\": \"danger\",
                \"fallback\": \"${TITLE}\",
                \"title\": \"${TITLE}\",
                \"text\": \"${MESSAGE}\"
                }]
  }" ${SL_WEBHOOKURL} > /dev/null
else
  sleep 15

  # Slack Title
  TITLE=${TITLE:-"Let's Encrypt更新完了通知"}

  # Slack Message
  MESSAGE=${MESSAGE:-"証明書を更新しました!"}

  #POST
  curl -s -S -X POST --data-urlencode "payload={
                \"channel\": \"${SL_CH_LETSENCRYPT}\",
                \"username\": \"${SL_BOTNAME}\",
                \"attachments\": [{
                \"color\": \"danger\",
                \"fallback\": \"${TITLE}\",
                \"title\": \"${TITLE}\",
                \"text\": \"${MESSAGE}\"
                }]
  }" ${SL_WEBHOOKURL} > /dev/null
fi

# Start nginx
/usr/sbin/service nginx start

Enter fullscreen mode Exit fullscreen mode

Results

If successful,
Screenshot 2017-07-01 15.46.02.png

If failed,
Screenshot 2017-07-01 15.45.56.png

It's nonsensical that it's red whether it succeeds or fails...

Top comments (0)