Search This Blog

Tuesday, June 07, 2016

Cloudflare API delete multiple records via Powershell

Recently whilst setting up cloudflare DNS, I had to delete a lot of records. With the API you can only do it one at a time. With thousands of records to remove I put together a little script tot do this.

Please ensure you fully test what you are doing with this, as I take no responsibility, but it worked for me.

You will various things to make this work, and I will assume you know how to use the API, by supplying your API key and email etc….

The script below can, with a small change, either read in the records to delete from a file or you can manually create the array in the script.

The script also contains output debugging that I left in.

Hope it helps somebody Smile

$headers = @{
"X-Auth-Key" = '<you need to get this from cloudflare>';
"X-Auth-Email" = '<replace this with email address>';
"Content-Type" = 'application/json'
}
#this may need changing when Cloudflare update the api
[string]$cloudFlareApiBaseUrl = "https://api.cloudflare.com/client/v4"
#file with records in it
[string]$recordlist= 'c:\path\fileRecordList.txt';
#dns domain to use
[string]$Zone = "contoso.com";

#Manually create array, add records here to delete.
<#
$ZoneRecords = @(
'example.contoso.com',
'example.subdomain.contoso.com'
)#>


#Create array from file, records to delete.
$ZoneRecords = Get-content -Path ".\${recordlist}"

# Get Zone ID from cloudflare
$request = Invoke-WebRequest -Uri "${cloudFlareApiBaseUrl}/zones/?name=${Zone}" -Method "GET" -Headers $headers
$zoneId = $(ConvertFrom-Json $request.Content).result[0].id

Foreach ($Element IN $ZoneRecords) {
#debug
$Element

#GET record info from cloudflare
$Record = Invoke-WebRequest -Uri "${cloudFlareApiBaseUrl}/zones/${ZoneId}/dns_records/?name=${Element}" -Method "GET" -Headers $headers
$RecordID = $(ConvertFrom-Json $Record.Content).result[0].id
$RecordName = $(ConvertFrom-Json $Record.Content).result[2].id

#debug
$Record

#DELETE record info from cloudflare
$RecordDelete = Invoke-WebRequest -Uri "${cloudFlareApiBaseUrl}/zones/${ZoneId}/dns_records/${RecordID}" -Method "DELETE" -Headers $headers

#debug
$RecordDelete
'RecordName:' + $RecordName;
'RecordID:' + $RecordID;
}

The format of the text file is just a flat text file

test.qa.contoso.com
test.demo.contoso.com
test.demo.contoso.com
test.contoso.com
test1.contoso.com
test2.contoso.com
test.qa2.contoso.com
test2.qa.contoso.com
test.training.contoso.com
test3.contoso.com
test4.contoso.com

Share/Bookmark

No comments:

Post a Comment