Skip to content

Instantly share code, notes, and snippets.

@amanjuman
Last active March 26, 2023 18:23
Show Gist options
  • Save amanjuman/5a813fdd20710df809041a057762029d to your computer and use it in GitHub Desktop.
Save amanjuman/5a813fdd20710df809041a057762029d to your computer and use it in GitHub Desktop.
Create a DNS record for multiple DNS zones in CloudFlare

Before you start, make sure you have the following information:

CloudFlare API key CloudFlare account email DNS Zone ID DNS record details (e.g. name, type, content, TTL) bash

#!/bin/bash

# Set variables
api_key="YOUR_CLOUDFLARE_API_KEY"
email="YOUR_CLOUDFLARE_ACCOUNT_EMAIL"
zone_ids=("ZONE_ID_1" "ZONE_ID_2") # Add all DNS Zone IDs here
name="example.com" # DNS record name
type="A" # DNS record type (e.g. A, CNAME, MX, etc.)
content="192.0.2.1" # DNS record content (e.g. IP address, hostname)
ttl="1" # TTL value in seconds

# Loop through all DNS Zone IDs
for zone_id in "${zone_ids[@]}"
do
    # Create JSON payload
    json="{\"type\":\"$type\",\"name\":\"$name\",\"content\":\"$content\",\"ttl\":$ttl}"

    # Make API request to create DNS record
    curl -X POST "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records" \
         -H "X-Auth-Email: $email" \
         -H "X-Auth-Key: $api_key" \
         -H "Content-Type: application/json" \
         --data "$json"

    # Add line break between each API request output
    echo ""
done

To use this script, simply replace the YOUR_CLOUDFLARE_API_KEY and YOUR_CLOUDFLARE_ACCOUNT_EMAIL with your actual API key and account email, and add all DNS Zone IDs to the zone_ids array.

You can also customize the DNS record details (e.g. name, type, content, TTL) to suit your needs.

Save the script in a file with a .sh extension (e.g. create_dns_record.sh), make it executable (chmod +x create_dns_record.sh), and run it using ./create_dns_record.sh.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment