背景
阿里云、腾讯云免费证书都从1年更改为了3个月,囊中羞涩的我有了使用Let‘s Encrypt证书的想法。
但是有个问题:如何自动上传Let's Encrypt证书到阿里云,毕竟Let‘s Encrypt证书的有效期也是3个月,每三个月手动操作也不现实那天就忘了。
解决
幸好阿里云的开放API的支持还不错,他的产品有各种语言的API接口供调用,由于之前有了acme.sh自动续期,因此使用Aliyun CLI来实现自动设置Aliyun CDN的证书。
-
下载Aliyun CLI
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz tar -zxvf aliyun-cli-linux-latest-amd64.tgz
-
设置AccessKey\AccessSecret
-
配置Aliyun CLI
root@drgon:/root# ./aliyun configure set \ --profile akProfile \ --mode AK \ --region cn-hangzhou \ --access-key-id 阿里云AccessKey\ --access-key-secret 阿里云AccessSecret
-
测试AccessKey是否正确: 查看当前证书
root@drgon:/root# ./aliyun cdn DescribeDomainCertificateInfo \ --region cn-hangzhou \ --profile akProfile \ --DomainName xx.example.com { "CertInfos": { "CertInfo": [ { "CertDomainName": "xx.example.com", "CertExpireTime": "2024-08-07T15:02:32Z", "CertId": "13875793", "CertLife": "2 months", "CertName": "xx.example.com", "CertOrg": "Let's Encrypt", "CertRegion": "cn-hangzhou", "CertStartTime": "2024-05-09T15:02:33Z", "CertType": "upload", "CertUpdateTime": "2024-06-30T22:38:51Z", "DomainCnameStatus": "ok", "DomainName": "xx.example.com", "ServerCertificate": "-----BEGIN CERTIFICATE-----\nMIIF7DCCBNSgSBHWnj0/8wJFUSFA\n----END CERTIFICATE-----\n", "ServerCertificateStatus": "on", "Status": "" } ] }, "RequestId": "DA1404C7-FC74-5AD6-BABF-40A293BD241C" }
当返回如上则说明配置正确
-
编写脚本
CRT_PATH="/ssl" #ssl证书存放位置,放入:cert.pem、privkey.pem Ali_Key="Ali_Key" #阿里云accesskey Ali_Secret="Ali_Secret" #阿里云accesssecret update_aliyun_cdn(){ aliyun_cdn_domain=${1:-"xx.example.com"} #默认xx.example.com # 设置阿里云Cli配置 ${BASE_ROOT}/aliyun configure set \ --profile akProfile \ --mode AK \ --region cn-hangzhou \ --access-key-id ${Ali_Key} \ --access-key-secret ${Ali_Secret} #获取SSL证书内容 SSLPubContent=$(cat "${CRT_PATH}/cert.pem") SSLPriContent=$(cat "${CRT_PATH}/privkey.pem") #更新域名证书 ${BASE_ROOT}/aliyun cdn SetCdnDomainSSLCertificate \ --DomainName ${aliyun_cdn_domain} \ --SSLPub="${SSLPubContent}" \ --SSLPri="${SSLPriContent}" \ --CertType upload \ --SSLProtocol on || { echo "Error setting SSL certificate for CDN domain"; exit 1; } }
-
测试脚本
root@drgon:/root# ./update_aliyun_cdn xx.example1.com begin upload to aliyun cdn domain: xx.example1.com cert.pem: /ssl/cert.pem { "RequestId": "1483FE80-F6C3-5DF6-9662-91C180DDB0C3" }
如上则说明执行成功
-
设置Cron定时任务
root@drgon:/root# crontab -e 0 0 1 * * /root/update_aliyun_cdn.sh