This week I was moving my test domains to cloudflare. The process is quick and easy. By default cloudflare is trying to migrate all of your DNS records and that is cool. Unfortunately when you have wildcard domain *
it can add 200 uneeded A records
to your domains. My first thought was ok not big deal I will remove them in bulk but you can remove entries only one by one... :)
Fortunetly to overcome this issue we can use cloudflare API! First step will be to create API token with DNS zone edit priviliges. The step by step manual is in the docs. We can verify the token using CURL:
curl -X GET "https://api.cloudflare.com/client/v4/user/tokens/verify" \
-H "Authorization: Bearer <token secret>" \
-H "Content-Type:application/json"
Next we have to retrive our DNS Zone id. we can find it dashboard. To get it we have to go to Websites ->our domain->Overview and on the right there will be Zone ID .
After that we will be interested in two specyfic API endpoints.
- List DNS records: https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
- Delete DNS record: https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record
To list all records we in the zone we have to make this call:
and to remove:
With those two API requests, little support from jq
and for
loop we are able to make small script that will clean it up for us :)
for dns_record in $(curl -X GET "https://api.cloudflare.com/client/v4/zones/<ZONE_ID/dns_records?page=1&per_page=300" -H "Authorization: Bearer <API TOKEN>" -H "Content-Type: application/json" | jq -r ".result [] .id")
do
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/<ZONE_ID>/dns_records/$dns_record" -H "Content-Type: application/json" -H "Authorization: Bearer <API TOKEN>"
done
And that is ready bash snippet that will remove all DNS records from selected zone :)