Skip to content

Instantly share code, notes, and snippets.

@kimboslice99
Created March 12, 2023 21:04
Show Gist options
  • Save kimboslice99/1533e1ab3eec8d7c7a448e69c338de76 to your computer and use it in GitHub Desktop.
Save kimboslice99/1533e1ab3eec8d7c7a448e69c338de76 to your computer and use it in GitHub Desktop.
Delete Cloudflare IP access rules older than X days
$email="CF_EMAIL"
$apikey="CF_API_KEY"
$deleted = 0
$records = 0
$page = 1
$pages = 1
while($page -le $pages){
Write-Host "########## $page ###########"
$data = (Invoke-WebRequest -Uri "https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules?page=$page" -Method 'GET' -ContentType "application/json" -Headers @{'Accept'='application/json';'X-Auth-Email'="$email";'X-Auth-Key'="$apikey"}).Content
$results = $data | ConvertFrom-Json
$pages = $results.result_info.total_pages
foreach($record in $results.result) {
$records++
Write-Host "########### $($record.id) ###########"
$id = $record.id
$cur_date = (Get-Date).AddDays(-30)
$record_time = Get-Date -Date $($record.created_on -replace "T", " " -replace "\..+") # parse damn you
if ($record_time -le $cur_date){
$record
Write-Host "Deleting record $id"
Invoke-WebRequest -Uri "https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules/$id" -Method 'DELETE' -ContentType "application/json" -Headers @{'Accept'='application/json';'X-Auth-Email'="$email";'X-Auth-Key'="$apikey"}
$deleted++
} else {
Write-Host "Not old enough $id"
$record
}
}
if($page -lt $pages){
$page++
} else {
break
}
}
Write-Host "Deleted $deleted records out of $records | got to page $page out of $pages"
@chattyaka
Copy link

Can you add domain validation? Because the script is deleting only records that apply to all websites. I need the records to be deleted only for a specific domain. Thank you

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