Let’s Encrypt の SSL 証明書を certbot と crontab で自動更新する設定方法

無料 SSL 証明書 Let’s Encrypt を certbot と crontab で自動更新させる設定方法をご紹介します。

Let’s Encrypt

前提条件

  • SSL 証明書: Let’s Encrypt
  • サーバー: Ubuntu 16.04.2 LTS
  • ウェブサービス: Mastodon

certbot コマンドのインストール

まず、certbot コマンドがインストールされているか確認します。

$ which certbot

certbot コマンドが無ければインストールしましょう。

$ sudo apt-get -y install certbot
 
[sudo] password for admin: 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
E: Unable to locate package certbot

E: Unable to locate package certbot エラーの対応方法

E: Unable to locate package certbot エラーが出たら add-apt-repository ppa:certbot してから再度インストールしましょう。

sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot

この手順でもエラーが発生したら、

を参考にして解決して下さい。

crontab に設定する command を手動実行

root ユーザの crontab に登録する command なので、同じ条件で手動実行したいので root ユーザになってから command を実行します。

sudo su -
/usr/bin/certbot renew --quiet --renew-hook "/bin/systemctl reload nginx"

command 実行後、念のため Nginx のプロセスが起動していることを確認しておきましょう。

$ systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2017-07-16 14:26:04 JST; 33s ago
  Process: 9024 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 9062 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 9039 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
 Main PID: 9072 (nginx)
    Tasks: 2
   Memory: 4.0M
      CPU: 33ms
   CGroup: /system.slice/nginx.service
           ├─9072 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
           └─9075 nginx: worker process

SSL 証明書の有効期限の確認

念のため SSL 証明書の有効期限が 90 日後に更新されていることを確認しましょう。

$ SSL_DOMAIN=yoursite.example.com
$ openssl s_client -connect $SSL_DOMAIN:443 < /dev/null 2> /dev/null | openssl x509 -text | grep 'Not After'
    Not After : Oct 14 04:26:00 2017 GMT

crontab に SSL 自動更新コマンド登録

sudo crontab -e

以下を追記します。

日本時間の毎月1日 午前4時に SSL 証明書を更新する crontab

# At 4:00 am on the 1st every month (JST)
00 19 1 * * /usr/bin/certbot renew --nginx --renew-hook "/bin/systemctl reload nginx"

念のため crontab にちゃんと登録されているか確認しておきましょう。

$ sudo crontab -l
# At 4:00 am on the 1st every month (JST)
00 19 1 * * /usr/bin/certbot renew --nginx --renew-hook "/bin/systemctl reload nginx"

私は途中で Let’s Encrypt SSL 証明書の自動更新を設定したのですが、忘れそうで怖いので面倒でも最初にやっておくことをオススメします。

以上、無料 SSL 証明書 Let’s Encrypt を自動更新したい、現場からお送りしました。

参考情報