Let's Encrypt 通配符证书自动续期大法

鉴于大部分免费SSL证书都是针对特定二级域名的,而 Let’s Encrypt 提供通配符证书,却需要每三个月续期一次,经过摸索,鼓捣出了一个方案,遂记录。

安装 certbot

鉴于 certbot 本身对各种系统自带的包管理工具支持一般,所以我们采用通用的方法,先安装 snap ,再使用 snap 安装 certbot。

以下示例环境为 CentOS8 ,其他系统可以参照 snap 官方安装文档

安装 snap

1
2
3
4
5
6
7
8
9
# 安装企业支持包
sudo dnf install epel-release
sudo dnf upgrade
# 安装 snap
sudo dnf install snapd
sudo systemctl enable --now snapd.socket
sudo ln -s /var/lib/snapd/snap /snap
sudo snap install core
sudo snap refresh core

成功效果

安装 cerbot

1
2
3
# 安装 cerbot
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

成功效果

实现自动续期

我的自动续期是使用了 Gayhub 一位老铁 ywdblog 开源的脚本,我选择的运行环境是 Python3。

1
2
dnf install -y python3
sudo ln -s /usr/bin/python3 /usr/bin/python

以下示例中我的域名为 wayneshao.com ,注册于腾讯云。

脚本所在目录为 /root/certbot-dns-au

配置证书

腾讯云后台新增一个密匙用于脚本自动配置域名解析来续期

申请密钥和key

将申请到的 SecretId 和 SecretKey 填入脚本中

1
vi /root/certbot-dns-au/au.sh

把key填入脚本

申请通配符证书

直接使用 ywdblog 老哥的脚本

1
certbot certonly  -d *.wayneshao.com --manual --preferred-challenges dns  --manual-auth-hook "/root/certbot-dns-au/au.sh python txy add" --manual-cleanup-hook "/root/certbot-dns-au/au.sh python txy clean"

申请通配符证书

申请证书成功后,可以直接在硬盘找到对应的文件(建议 NGINX 等软件使用证书时,直接使用原本的目录,方便续期)。

续期通配符证书

因为我的证书最终被部署到了 NGINX ,故而我做了续期成功后的 hook ,对 NGINX 的配置做了刷新。

1
certbot renew --cert-name wayneshao.com --deploy-hook  "nginx -s reload" --manual-auth-hook "/root/certbot-dns-au/au.sh python txy add" --manual-cleanup-hook "/root/certbot-dns-au/au.sh python txy clean"

由于有效期还长续期失败

证书有效期小于30天时才能续期成功,由于有效期还长,续期失败。

使用定时任务自动续期

流程已经畅通,接下来就是要把自动续期的脚本加入 crontab ,每天去尝试一下,防止证书过期。

1
crontab -e

新加一行 输入

1
1 1 */1 * * root certbot renew --cert-name wayneshao.com --deploy-hook  "nginx -s reload" --manual-auth-hook "/root/certbot-dns-au/au.sh python txy add" --manual-cleanup-hook "/root/certbot-dns-au/au.sh python txy clean"

查看确认一下

1
crontab -l

定时任务列表

欢迎关注我的其它发布渠道