Assistance with Cloudflare PHP script to create rule with all zones on account

I seem to be having a problem to get this script to write a rule to each zone. There are 200+ zones on the account, so I need some sort of automation to do this.

I receive the following error for each zone ID when the script is run:

Failed to create WAF rule for Zone ID: XXXXXXXXXXXXXXXXXXX: Could not route to /zones/XXXXXXXXXXXX/firewall/waf/rules, perhaps your object identifier is invalid? No route for that URI Zone

The looping through each zone portion of the script works fine.

I am trying for this to apply this rule using this php code:

<?php
// Cloudflare API credentials
$authKey = '123456';
$authEmail = '[email protected]';

$apiEndpoint = 'https://api.cloudflare.com/client/v4/zones?page=1&per_page=300'; // Cloudflare API endpoint

$wafRuleData = [
    'description' => 'Block Countries',
    'action' => 'block',
    'priority' => 1,
    'filter' => [
        'expression' => '(ip.geoip.country ne "US" and ip.geoip.country ne "CA" and ip.geoip.country ne "GB" and ip.src ne 165.227.239.229 and ip.src ne 178.62.5.35)',
    ],
    'paused' => false,
];

$headers = [
    'X-Auth-Key: ' . $authKey,
    'X-Auth-Email: ' . $authEmail,
    'Content-Type: application/json'
];

// Sample callAPI function to make API requests
function callAPI($method, $url, $headers, $data = false)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

    if ($data) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);

    if ($response === false) {
        echo 'Error: ' . curl_error($ch);
    }

    curl_close($ch);

    return json_decode($response, true);
}

// Initialize cURL session
$ch = curl_init($apiEndpoint);

// Set cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Execute the request
$response = curl_exec($ch);

// Check if request was successful
if ($response === false) {
    echo 'Error: ' . curl_error($ch);
} else {
    // Decode JSON response
    $responseData = json_decode($response, true);

    // Check if zones are retrieved successfully
    if (isset($responseData['result'])) {
        $zones = $responseData['result'];

        // Display list of zones
        echo "List of Cloudflare zones:<br>";
        foreach ($zones as $zone) {
            $zoneID = $zone['id'];
            echo "Zone Name: " . $zone['name'] . "<br>";

  // Create WAF rule for each zone
$wafRuleURL = 'https://api.cloudflare.com/client/v4/zones/' . $zoneID . '/firewall/waf/rules';
$createWAFRule = callAPI('POST', $wafRuleURL, $headers, $wafRuleData);

// Check the response or handle errors here
if ($createWAFRule && isset($createWAFRule['success']) && $createWAFRule['success']) {
    echo "WAF rule created for Zone ID: {$zoneID}\n";
} else {
    echo "Failed to create WAF rule for Zone ID: {$zoneID}: ";
    if (isset($createWAFRule['errors'])) {
        foreach ($createWAFRule['errors'] as $error) {
            echo $error['message'] . "\n";
        }
    } else {
        echo "Unknown error\n";
    }
    // Handle errors if needed
}
        }
    } else {
        echo 'Failed to retrieve zones. Error: ' . $responseData['errors'][0]['message'];
    }
}

// Close cURL session
curl_close($ch);
?>

Is there anyone that can provide some advice here? Much appreciated!

A few people have confused this recently (I’ll try and find the posts). You need to use the rulesets API to set the rules…

[add]
Here…

1 Like

Hi SJR … thanks for the reply. I appreciate your note … but I’m not sure what to do with info in your suggested post. Not sure I follow it.

Also … I’m creating a NEW rule in cloudflare for each zone. I’m not updating/editing a specific rule, which is what the link you posted refers to.

Thanks again.

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.