When I start to use let’s encrypt ssl certificate, I should renew it per 3 months manually, if I forgot it sometimes, the website would show safty warnings. Today I want to research how to renew the certificate automatically.
First, I should download aliyun tool.
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
tar xzvf aliyun-cli-linux-latest-amd64.tgz
mv aliyun /usr/local/bin
Set certbot-dns-aliyun.
#!/bin/bash
FLAG="(\.com\.cn|\.gov\.cn|\.net\.cn|\.org\.cn|\.ac\.cn|\.gd\.cn)$"
if ! command -v aliyun >/dev/null; then
echo "ERROR: You should install aliyun tool first. https://help.aliyun.com/document_detail/121541.html。" 1>&2
exit 1
fi
DOMAIN=$(expr match "$CERTBOT_DOMAIN" '.*\.\(.*\..*\)')
SUB_DOMAIN=$(expr match "$CERTBOT_DOMAIN" '\(.*\)\..*\..*')
if echo $CERTBOT_DOMAIN |grep -E -q "$FLAG"; then
DOMAIN=`echo $CERTBOT_DOMAIN |grep -oP '(?<=)[^.]+('$FLAG')'`
SUB_DOMAIN=`echo $CERTBOT_DOMAIN |grep -oP '.*(?=\.[^.]+('$FLAG'))'`
fi
if [ -z $DOMAIN ]; then
DOMAIN=$CERTBOT_DOMAIN
fi
if [ ! -z $SUB_DOMAIN ]; then
SUB_DOMAIN=.$SUB_DOMAIN
fi
if [ $# -eq 0 ]; then
aliyun alidns AddDomainRecord \
--DomainName $DOMAIN \
--RR "_acme-challenge"$SUB_DOMAIN \
--Type "TXT" \
--Value $CERTBOT_VALIDATION
/bin/sleep 20
else
RecordId=$(aliyun alidns DescribeDomainRecords \
--DomainName $DOMAIN \
--RRKeyWord "_acme-challenge"$SUB_DOMAIN \
--Type "TXT" \
--ValueKeyWord $CERTBOT_VALIDATION \
| grep "RecordId" \
| grep -Eo "[0-9]+")
aliyun alidns DeleteDomainRecord \
--RecordId $RecordId
fi
Save these codes into alidns.sh, and use chmod u+x grand execute privilege to the sh file, and use “mv alidns.sh /usr/local/bin/alidns” to remove the sh file to /usr/local/bin.
Execute aliyun command to set aliyun configurations.
aliyun configure set \
--profile AkProfile \
--mode AK \
--access-key-id **** \
--access-key-secret **** \
--region ****
If you don’t know the region id, you could try to search it at https://help.aliyun.com/zh/ecs/product-overview/regions-and-zones?spm=a2c4g.11186623.0.0.212c33afo1tLPk#concept-2459516 this page.
When you want to apply a new certificate, you could execute this command:
certbot certonly -d *.example.com --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean" --dry-run
But when you want to application in productive environment, you should remove “–dry-run” param.
When you want to renew a certificate, you could execute this command:
certbot renew --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean" --dry-run
For the same reason, you should remove the param “–dry-run” when you use it in productive environment.
At last, we should add a schedule task on our server, so we could add this command into crontab file:
1 1 */1 * * root certbot renew --manual --preferred-challenges dns --manual-auth-hook "alidns" --manual-cleanup-hook "alidns clean" --deploy-hook "nginx -s reload"