Skip to content

Instantly share code, notes, and snippets.

@EmberHeartshine
Created April 18, 2022 13:08
Show Gist options
  • Save EmberHeartshine/8559e49d9c44ed038d324ba927b62918 to your computer and use it in GitHub Desktop.
Save EmberHeartshine/8559e49d9c44ed038d324ba927b62918 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 subdomains)
#!/bin/bash
APITOKEN="none"
if [ ! $1 ] || [ ! $2 ]; then
echo -e "Usage:\n\t"$0" <subdomain> <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="$2 -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"."$2 -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"."$2 -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'.'$2'","content":"'$CNAMEREC'","ttl":1,"proxied":false}' >/dev/null
echo "CF cache for "$1"."$2" disabled. Sleeping 5m to allow SSH cert to re-assert..."
sleep 5m
CERTDATE=$(echo |openssl s_client -servername $1.$2 -connect $1.$2: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"."$2" 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'.'$2'","content":"'$CNAMEREC'","ttl":1,"proxied":true}' >/dev/null
echo $1"."$2" LE cert not near expiration. Turning CF cache back on."
fi
else
echo $1" is not a valid CNAME record for zone "$2"!"
fi
else
echo $2" 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