Created
November 28, 2025 15:24
-
-
Save faryar76/96c02468ea8607b75a248a3b3ead81c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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