Cloudflare delete dns records in bulk

Categories: cloudflare

During the process of adding a domain to Cloudflare, they scan the current dns records and create them for you, which is very nice. However this can also be annoying. I have a case where we bought a domain just to own it for future use, moved it to cloudflare and they created 60+ dns records for me. We’re not going to use this domain right now, so I just wanted to delete the records and add a few spf, dmarc records to prevent the mail from being used for emails. Apparently there is no way to do a bulk deletion from they webinterface and I’m lazy, so fortunately this can be done by using their REST API, So I created the script below.

Feel free to use my script, you just need to do the following:

  • Create a API Token for the specified domain with DNS edit permissions
  • Copy the Zone ID for the specific domain
#!/bin/bash 
# Author: Kenneth
# Date: 17/3/2023
#

token="<API Token>" # Replace <API Token> with your token
zone_id="<Zone ID>" # Repace <Zone ID> with your domains Zone ID

# Test Token:
function test_token() {
curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
     -H "Authorization: Bearer $token" \
     -H "Content-Type:application/json"
}

# List Records in zoneid
function list_records() {
curl -X GET "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records" \
	 -H "Authorization: Bearer $token" \
     -H "Content-Type: application/json"
}

# Delete Records in zone
function delete_records() {
printf "\n 
    $(curl -X DELETE "https://api.cloudflare.com/client/v4/zones/$zone_id/dns_records/$1" \
  	       -H "Authorization: Bearer $token" \
  	       -H "Content-Type: application/json")
"
}

# Loop through records
function main(){
  list_records | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^id/ {print $2}' | sed 's/^.//' | sed 's/.$//' | while read record_id ; do
		delete_records $record_id
  done 
}

main