Skip to content

Instantly share code, notes, and snippets.

@ruanimal
Created September 18, 2022 04:35
Show Gist options
  • Save ruanimal/23bad5a3ed73909f58281ebacc1fea99 to your computer and use it in GitHub Desktop.
Save ruanimal/23bad5a3ed73909f58281ebacc1fea99 to your computer and use it in GitHub Desktop.
certbot-renew-cloudflare
#!/bin/bash
# usage: /usr/bin/certbot renew --manual-auth-hook="/root/cloudflare-update-dns.sh" --post-hook "nginx -s reload"
if [[ -z "$(command -v dig)" || -z "$(command -v jq)" || -z "$(command -v curl)" ]]; then
apt install dnsutils jq curl -y
fi
DIR="$(dirname "$0")"
CHALLENGE_DOMAIN="_acme-challenge.${CERTBOT_DOMAIN}"
CLOUDFLARE_ZONE=your-dns-zone
CLOUDFLARE_TOKEN=your-dns-api-token
DNS_SERVER=8.8.8.8
echo "CHALLENGE_DOMAIN: ${CHALLENGE_DOMAIN}"
echo "CHALLENGE_VALUE: ${CERTBOT_VALIDATION}"
echo "DNS_SERVER: ${DNS_SERVER}"
echo "ZONE: ${CLOUDFLARE_ZONE}"
function cleanup() {
records=($(curl -X GET "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE}/dns_records?type=TXT&name=${CHALLENGE_DOMAIN}&page=1&per_page=100" \
-H "Authorization: Bearer ${CLOUDFLARE_TOKEN}" \
-H "Content-Type: application/json" -s | jq -r ".result[].id"))
echo "${records}"
for record in "${records[@]}"; do
echo "clean: $record"
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE}/dns_records/${record}" \
-H "Authorization: Bearer ${CLOUDFLARE_TOKEN}" \
-H "Content-Type: application/json" -s | jq -r "[.success, .errors[].message] | @csv"
done
}
function update() {
ADD_RECORD_RESULT=$(curl -X POST "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE}/dns_records" \
-H "Authorization: Bearer ${CLOUDFLARE_TOKEN}" \
-H "Content-Type: application/json" \
--data "{\"type\":\"TXT\",\"name\":\"${CHALLENGE_DOMAIN}\",\"content\":\"${CERTBOT_VALIDATION}\", \"ttl\": 120}" -s | jq -r "[.success, .errors[].message] | @csv")
echo "Add record result: ${ADD_RECORD_RESULT}"
if [[ ! $(echo "${ADD_RECORD_RESULT}" | grep "true") ]]; then
echo "Add record failed, exit"
exit 1
fi
while true; do
records=$(dig -t TXT ${CHALLENGE_DOMAIN} @${DNS_SERVER} +noall +answer +short | grep "${CERTBOT_VALIDATION}")
if [[ ${records} ]]; then
break
fi
echo "DNS records have not been propagate, sleep 5s..."
sleep 5
done
echo "DNS record have been propagated, finish"
}
cleanup && sleep 1 && update && sleep 10
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment