使用Certbot申请免费 SSL 证书及自动续期
本文解决了阿里云 DNS 不能自动为通配符证书续期的问题
原理
当我们使用 certbot
申请通配符证书时,需要手动添加 TXT 记录。每个 certbot 申请的证书有效期为 3 个月,虽然 certbot
提供了自动续期命令,但是当我们把自动续期命令配置为定时任务时,我们无法手动添加新的 TXT 记录用于 certbot
验证。
好在 certbot
提供了一个 hook,可以编写一个 Shell 脚本。在续期的时候让脚本调用 DNS 服务商的 API 接口动态添加 TXT 记录,验证完成后再删除此记录。
安装
安装 aliyun cli 工具
1
2
3
4wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
tar xzvf aliyun-cli-linux-latest-amd64.tgz
sudo cp aliyun /usr/local/bin
rm aliyun安装完成后需要配置凭证信息
安装 certbot-dns-aliyun 插件
1
2
3
4
5wget https://www.zhangyirui.cn/files/alidns.sh
sudo cp alidns.sh /usr/local/bin
sudo chmod +x /usr/local/bin/alidns.sh
sudo ln -s /usr/local/bin/alidns.sh /usr/local/bin/alidns
rm alidns.sh申请证书
测试是否能正确申请:
1
certbot certonly -d *.example.com --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean" --dry-run
正式申请时去掉
--dry-run
参数:1
certbot certonly -d *.example.com --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean"
证书续期
1
certbot renew --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean" --dry-run
如果以上命令没有错误,把
--dry-run
参数去掉。自动续期
添加定时任务 crontab。
1
crontab -e
输入
1
1 1 */1 * * root certbot renew --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean" --deploy-hook "nginx -s reload"
上面脚本中的
--deploy-hook "nginx -s reload"
表示在续期成功后自动重启 nginx。
- 标题: 使用Certbot申请免费 SSL 证书及自动续期
- 作者: 静凇
- 创建于 : 2023-12-29 21:54:38
- 更新于 : 2025-04-28 01:11:10
- 链接: https://blog.zhangyirui.cn/2023/12/29/certbot-dns-aliyun/
- 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。