LoginSignup
232
215

More than 5 years have passed since last update.

Let's Encryptを使ってSSL証明書を自動更新する(AWS/Amazon Linux/Apache)

Last updated at Posted at 2017-03-21

Let's Encryptとは

詳しい説明はこちら。要は、

  • 無料で
  • 自動更新できる
  • SSL証明書導入システム

環境

  • AWS Amazon Linux
  • Apache 2.4.23

手順

全部rootでやってますが、適宜読み替えてください。

Let's Encryptのインストール

terminal
sudo curl https://dl.eff.org/certbot-auto -o /usr/bin/certbot-auto
sudo chmod 700 /usr/bin/certbot-auto

あるいは各種パッケージ管理システムを使ってインストール

証明書の作成

terminal
sudo /usr/bin/certbot-auto certonly --webroot -w /var/www/html --email test@example.com --debug -d test.example.com
  • 必要があれば、関係するパッケージが更新・インストールされる。その場合は、再度上のコマンドを入れないといけないかも。
  • dオプションでドメインを指定するが、-d example.com -d test.example.comのように複数指定できる。最初に記述したドメインがコモンネームになる。
    • ちなみに、指定するすべてのドメインは、このサーバに向いたAレコードを持っていないといけない。
    • wオプションでドキュメントルートディレクトリを指定する。ドメインごとに別のドキュメントルートディレクトリを指定したいときには、-dオプションの直前に-wオプションを書けば良い。
  • すべて完了すると、 下記のパスに証明書と鍵が発行される。
/etc/letsencrypt/live/test.example.com/fullchain.pem 
/etc/letsencrypt/live/test.example.com/privkey.pem

証明書の指定

ここは、通常のApacheの指定と変わらない。nginxでも同様でしょう。例えば下記のような感じ。

terminal
sudo vi /etc/httpd/conf.d/ssl.conf
/etc/httpd/conf.d/ssl.conf
SSLCertificateFile /etc/letsencrypt/live/test.example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/test.example.com/privkey.pem

で、サーバ再起動。ブラウザで開いて確認しましょう。

terminal
sudo service httpd restart

自動化

Let's Encryptは3ヶ月しか有効期限がないので、自動更新するとよい。更新のためのコマンドをcronする。
まず、下記のコマンドが正常に動作し、証明書が更新されるかをテスト。

terminal
sudo /usr/bin/certbot-auto renew --post-hook "sudo service httpd restart"

renewは、すべての証明書を更新するコマンド。--post-hookオプションで指定したコマンドは、renew後に実行される。ただし、renewは期限が迫らないうちは、実行がスキップされ、その場合はpost-hookも実行されない。
いまは証明書を発行したばかりなので、下記のように表示されれば、問題なし。

terminal
-------------------------------------------------------------------------------
Processing /etc/letsencrypt/renewal/test.example.com.conf
-------------------------------------------------------------------------------
Cert not yet due for renewal

The following certs are not due for renewal yet:
  /etc/letsencrypt/live/test.example.com/fullchain.pem (skipped)
No renewals were attempted.
No hooks were run.

OKなら、cronに登録する。まずcronが動いているか確認しよう。

terminal
/etc/rc.d/init.d/crond status

cronに登録するファイルを作成し、以下を記入する。
crontab -eつかっちゃだめ。ぜったい。

terminal
sudo vi /etc/cron.d/letsencrypt
/etc/cron.d/letsencrypt
00 16 * * 2 root /usr/bin/certbot-auto renew --post-hook "service httpd restart"

この例では、毎週火曜の16時にrenewが起動する。
設定が終わったら、実際に起動して更新されるか、期限30日前の火曜に確認しよう。

ちなみに最近は…

Wordpressを構築するときなどは、上記のようなゼロからの構築はあんまりしていなくて、
Kusanagiのプロビジョニング過程で自動的にLet's Encryptが設定される、というのを利用しています。超ラク。
Kusanagiは無料、簡単、速いという三拍子揃っていて素晴らしいのでWordpress構築時にはみんな使うと良いと思う。

232
215
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
232
215