Skip to content

Instantly share code, notes, and snippets.

@faryar76
Created November 28, 2025 15:24
Show Gist options
  • Select an option

  • Save faryar76/96c02468ea8607b75a248a3b3ead81c4 to your computer and use it in GitHub Desktop.

Select an option

Save faryar76/96c02468ea8607b75a248a3b3ead81c4 to your computer and use it in GitHub Desktop.
#!/bin/bash
# -------------------------
# CONFIGURATION
# -------------------------
CF_API_TOKEN="YOUR_API_TOKEN" # Replace with your Cloudflare API token
ZONE_ID="YOUR_ZONE_ID" # Replace with your Cloudflare zone ID
SUBDOMAIN="subdomain.example.com" # Replace with your full subdomain
TTL=120 # DNS TTL in seconds
PROXIED=false # true to enable Cloudflare proxy, false to disable
# -------------------------
# GET CURRENT PUBLIC IP
# -------------------------
MYIP=$(curl -s https://ipv4.icanhazip.com)
if [ -z "$MYIP" ]; then
echo "❌ Could not retrieve public IP"
exit 1
fi
echo "Current public IP: $MYIP"
# -------------------------
# CHECK IF RECORD EXISTS
# -------------------------
RECORD_ID=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?type=A&name=$SUBDOMAIN" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" | jq -r '.result[0].id')
# -------------------------
# CREATE OR UPDATE A RECORD
# -------------------------
if [ "$RECORD_ID" = "null" ]; then
echo "Creating new A record for $SUBDOMAIN..."
RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"$SUBDOMAIN\",\"content\":\"$MYIP\",\"ttl\":$TTL,\"proxied\":$PROXIED}")
else
echo "Updating existing A record for $SUBDOMAIN..."
RESPONSE=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
-H "Authorization: Bearer $CF_API_TOKEN" \
-H "Content-Type: application/json" \
--data "{\"type\":\"A\",\"name\":\"$SUBDOMAIN\",\"content\":\"$MYIP\",\"ttl\":$TTL,\"proxied\":$PROXIED}")
fi
# -------------------------
# CHECK RESPONSE
# -------------------------
SUCCESS=$(echo $RESPONSE | jq -r '.success')
if [ "$SUCCESS" = "true" ]; then
echo "✅ DNS record synced successfully!"
else
echo "❌ Failed to sync DNS record:"
echo $RESPONSE
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment