Skip to content

Instantly share code, notes, and snippets.

@EmberHeartshine
Last active April 18, 2022 13:12
Show Gist options
  • Save EmberHeartshine/9a6274a204e01cefb962ef5b7f397bcc to your computer and use it in GitHub Desktop.
Save EmberHeartshine/9a6274a204e01cefb962ef5b7f397bcc to your computer and use it in GitHub Desktop.
Allow Github Pages to refresh the Letseyncrypt SSL cert and re-enable Cloudflare's cache configuration. (For apex-level domains)
#!/bin/bash
APITOKEN="none"
if [ ! $1 ]; then
echo -e "Usage:\n\t"$0" <zone>"
elif [ $APITOKEN == "none" ]; then
echo -e "Required configuration not found.\n\tAPI Token:\t"$APITOKEN
else
ZONEREC=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name="$1 -H "Authorization: Bearer "$APITOKEN -H "Content-Type:application/json")
if [ $(echo $ZONEREC |jq -j '.result[0].id') != null ]; then
ZONEID=$(echo $ZONEREC |jq -j '.result[0].id')
DNSREC=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/"$ZONEID"/dns_records?type=CNAME&name="$1 -H "Authorization: Bearer "$APITOKEN -H "Content-Type:application/json")
if [ $(echo $DNSREC |jq -j '.result[0].id' ) != null ]; then
CNAMEREC=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/"$ZONEID"/dns_records?type=CNAME&name="$1 -H "Authorization: Bearer "$APITOKEN -H "Content-Type:application/json" |jq -j '.result[0].content')
DNSID=$(echo $DNSREC |jq -j '.result[0].id')
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/"$ZONEID"/dns_records/"$DNSID -H "Authorization: Bearer "$APITOKEN -H "Content-Type:application/json" --data '{"type":"CNAME","name":"'$1'","content":"'$CNAMEREC'","ttl":1,"proxied":false}' >/dev/null
echo "CF cache for "$1" disabled. Sleeping 5m to allow SSH cert to re-assert..."
sleep 5m
CERTDATE=$(echo |openssl s_client -servername $1 -connect $1:443 2>/dev/null |openssl x509 -noout -dates |grep notAfter |cut -d '=' -f 2 |date -f - +"%Y%m%d")
NOWDATE=$(date +"%Y%m%d")
# The below is for testing only.
# echo $CERTDATE
# echo $NOWDATE
if [ $NOWDATE -gt $(date -d "$CERTDATE -3 days" +"%Y%m%d") ]; then
echo $1" LE cert near expiration. Leaving CF cache off."
exit
else
curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/"$ZONEID"/dns_records/"$DNSID -H "Authorization: Bearer "$APITOKEN -H "Content-Type:application/json" --data '{"type":"CNAME","name":"'$1'","content":"'$CNAMEREC'","ttl":1,"proxied":true}' >/dev/null
echo $1" LE cert not near expiration. Turning CF cache back on."
fi
else
echo $1" is not a valid CNAME record!"
fi
else
echo $1" is not a valid zone for this API token!"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment