Skip to content

Instantly share code, notes, and snippets.

@amanjuman
Last active May 7, 2024 06:16
Show Gist options
  • Save amanjuman/d87bf5a6faf029e80345ec043efd8feb to your computer and use it in GitHub Desktop.
Save amanjuman/d87bf5a6faf029e80345ec043efd8feb to your computer and use it in GitHub Desktop.
Remove all DNS records for a DNS Zone in CloudFlare using bash script

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

CloudFlare API key DNS Zone ID

API should have Zone Read, Write permission.

#!/bin/bash

# Set variables
api_token="YOUR_CLOUDFLARE_API_KEY"
zone_id="ZONE_ID"

# Get all DNS records for the zone
dns_records=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records" \
                 -H "Authorization: Bearer $api_token" \
                 -H "Content-Type: application/json")

# Check for successful API response
if [[ $(echo $dns_records | jq -r '.success') != "true" ]]; then
    echo "API call failed, details below:"
    echo $dns_records | jq '.errors'
    exit 1
fi

# Extract DNS record IDs, handling cases where no records are present
ids=$(echo $dns_records | jq -r '.result[]?.id // empty')

# Check if there are any DNS records to delete
if [[ -z "$ids" ]]; then
    echo "No DNS records found for deletion."
    exit 0
fi

# Loop through all DNS record IDs and delete them
for id in $ids
do
    echo "Deleting DNS record with ID: $id"
    delete_response=$(curl -s -X DELETE "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$id" \
                      -H "Authorization: Bearer $api_token" \
                      -H "Content-Type: application/json")

    # Optional: Check response of DELETE operation
    if [[ $(echo $delete_response | jq -r '.success') != "true" ]]; then
        echo "Failed to delete DNS record with ID: $id, details below:"
        echo $delete_response | jq '.errors'
    else
        echo "Successfully deleted DNS record with ID: $id"
    fi
done

echo "All DNS records for DNS Zone with ID $zone_id have been deleted."

This script you need to install jq if not installed already, example for ubuntu apt install -y jq To use this script, simply replace the YOUR_CLOUDFLARE_API_KEY and ZONE_ID with your actual API key and DNS Zone ID.

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

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