edo1z blog

プログラミングなどに関するブログです

Let's Encryptの更新方法と更新の自動化

この投稿でLet's Encryptで無料でSSL証明書を作りましたが有効期限が切れそうなので更新します。 環境は、サーバはさくらのVPS、OSはUbuntu16.04、webサーバはnginxです。

更新方法

参考:https://certbot.eff.org/#ubuntuxenial-nginx

Automating renewal

有効期限が切れる前に自動的に証明書を更新するようにCertbotを設定することができます。 Let's Encrypt Encryptは90日間使用できるので、この機能を利用することをお勧めします。このコマンドを実行すると、証明書の自動更新をテストできます。
$ letsencrypt renew --dry-run --agree-tos
Ubuntu Xenial上のCertbotのバージョンに「電子メールなしで登録する!」という警告が表示されるバグがあります。以前にCertbotに電子メールを送っていたとしても。これが起こっても心配しないでください。更新には影響しません。それが正しく動作していると思われる場合は、以下を実行するcronまたはsystemdジョブを追加して自動更新を手配できます
$ letsencrypt renew

更新する

更新はNginxをとめないといけません。止めずにrenewコマンドを実行すると、エラーがでます。

The program nginx (process ID 22394) is already listening on TCP port 80. This
will prevent us from binding to that port. Please stop the nginx program
temporarily and then try again. For automated renewal, you may want to use a
script that stops and starts your webserver. You can find an example at
https://letsencrypt.org/howitworks/#writing-your-own-renewal-script.
Alternatively you can use the webroot plugin to renew without needing to stop
and start your webserver.

手動で更新する

Nginxを停止したのちに、renewコマンドを実行して、Nginxを再開するか、webrootプラグインを利用して、renewコマンドを実行する必要があります。webrootプラグインを利用する場合、80ポートにアクセスしてNot Foundとかにならないようにする必要があるようです。私の場合、httpsでしか接続できない(httpの場合強制的にhttpsにリダイレクトさせる)ようにしてあるので、webrootは使えませんでした。Nginx停止&再開をrenewコマンドの前後でやってみます。

$ sudo systemctl stop nginx.service
$ letsencrypt renew
$ sudo systemctl start nginx.service

自動更新させる

自動更新はcronを使います。

$ cd
$ vim .crontab

.crontabの中身を下記のようにします。

0 3 15 * * systemctl stop nginx.service; letsencrypt renew; systemctl start nginx.service

あるいは、ログを残しておく場合は下記のようにします。

0 3 15 * * systemctl stop nginx.service; letsencrypt renew > /var/log/cron.log 2>&1; systemctl start nginx.service

crontabに反映させます。

$ crontab .crontab
$ crontab -l
0 3 15 * * systemctl stop nginx.service; letsencrypt renew; systemctl start nginx.service

設定がうまく反映できているかの確認をしたい場合、一旦上記cronの実行頻度を変更してすぐに実行させるようにしつつ、下記のような感じでログ出力したらいいと思います。

* * * * * systemctl stop nginx.service; letsencrypt renew >> /var/log/cron.log 2>&1; systemctl start nginx.service