令 acme.sh 使用 Cloudflare 的 DNS API 签发与续签证书

使用 acme.sh 通过 DNS 挑战的方式申请泛域名证书,且通过这种方式,我们可以很方面的申请 SSL 证书用于我们的内部服务,不会遇到因为使用自签名证书导致的各种麻烦。

acme.sh 支持非常多的 DNS 提供商的 DNS API,通过 DNS API 可以免去手动填写 _acme-challenge 的麻烦。

以 Cloudflare 为例

首先我们查看一下 acne.sh 需要 Cloudflare 什么信息:dns_cf.sh

#!/usr/bin/env sh
# shellcheck disable=SC2034
dns_cf_info='CloudFlare
Site: CloudFlare.com
Docs: github.com/acmesh-official/acme.sh/wiki/dnsapi#dns_cf
Options:
CF_Key API Key
CF_Email Your account email
OptionsAlt:
CF_Token API Token
CF_Account_ID Account ID
CF_Zone_ID Zone ID. Optional.
'

也可以看 acme.sh 的 wiki 是怎么写的,不过我觉得代码比 wiki 更诚实一点:

As of June 2025, the Cloudflare Domain API can be accessed using three kinds of API keys:

User token; Account-owned token; or User Global API Key (Not recommended).

我们采用第一个方法,User token.

去 Cloudflare 的控制面板拿到如下的凭证,然后再补充一下 CF_Email

Terminal window
CF_Token="Y7VRjJ_**"
CF_Zone_ID="5f011**"
CF_Account_ID="29b0**"
CF_Email="***"

不管是签发还是续签,添加 --dns_cf 参数即可

Terminal window
# 续签
/usr/share/acme.sh/acme.sh --cron --dns_cf --home /certs
# 签发
/usr/share/acme.sh/acme.sh --issue -d krystzal.dev --dns_cf --home /certs

使用 systemd-timer 来实现定时刷新

我们可以使用 systemd-timer 来替代 crontab 实现定时续签,这里以每天续签为例

# acme.sh.service
[Unit]
Description=Renew certificates acquired via acme.sh
After=network.target network-online.target nss-lookup.target
Wants=network-online.target nss-lookup.target
Documentation=https://github.com/acmesh-official/acme.sh/wiki
[Service]
User=cert
Group=cert
Type=simple
ExecStart=/bin/acme.sh --cron --dns dns_cf --home /certs --dnssleep 600
SuccessExitStatus=0 2
Restart=on-failure
EnvironmentFile=/etc/systemd/system/acme.sh.env
# acme.sh.timer
[Unit]
Description=Run acme.sh daily
[Timer]
OnCalendar=*-*-* 00:00:00
Persistent=true
[Install]
WantedBy=timers.target
Terminal window
# acmd.sh.env
CF_Token="Y7VRjJ_**"
CF_Zone_ID="5f011**"
CF_Account_ID="29b0**"

然后执行一下刷新 systemd-daemon,接着启用一下 acme.sh.timer

Terminal window
systemctl daemon-reload
systemctl enable acme.sh.timer

支持的 DNS API 列表

NOTE

这个列表更新于 2026-02-25,而 acme.sh 会随着时间更新,因此请查看其仓库获得最新的列表

在每个 DNS API 具体操作的 .sh 的文件开头有写需要什么 API密钥,前往 DNS 服务商面板获取后写作具体的环境变量即可