The ServiceNow Cloudflare integration enables organizations to automatically create incidents from security events, DDoS attacks, and WAF rule violations while maintaining an up-to-date CMDB of DNS zones and security configurations. This integration is essential for security operations teams managing web applications and infrastructure protected by Cloudflare's CDN and security services. The integration supports bidirectional data flows where Cloudflare webhooks push security events to ServiceNow for incident creation, while ServiceNow can query Cloudflare's REST API to retrieve zone configurations, analytics data, and update DNS records. The primary automation pattern uses Scripted REST APIs to receive webhook payloads and Business Rules or Flow Designer to process events, with the core functionality residing in the IT Service Management and Configuration Management modules.
Prerequisites
- •ServiceNow Tokyo release or later with Event Management plugin activated
- •Cloudflare account with Pro, Business, or Enterprise plan for webhook access
- •ServiceNow Integration Hub Professional license for advanced webhook processing
- •System Administrator or integration_admin role in ServiceNow
- •Cloudflare API token with Zone:Read, Zone.Zone:Read, and Zone.Analytics:Read permissions
- •Access to create and manage Scripted REST APIs in ServiceNow
- •Basic understanding of Cloudflare security features and zone management
Architecture Overview
The integration primarily uses ServiceNow's Scripted REST API framework to receive Cloudflare webhook notifications, with no official Integration Hub spoke available for Cloudflare at this time. Authentication is established using Cloudflare API tokens stored in ServiceNow Connection & Credential Aliases, enabling secure outbound API calls to retrieve zone data and analytics. The data flow is bidirectional with Cloudflare webhooks pushing security events inbound to ServiceNow via HTTPS, while ServiceNow makes outbound REST calls to query Cloudflare's API for CMDB updates and incident enrichment. No MID Server is required as all communication occurs over HTTPS through ServiceNow's built-in REST capabilities, though rate limiting applies with Cloudflare's API allowing 1,200 requests per 5-minute window for most endpoints. The implementation leverages RESTMessageV2 for outbound calls, GlideScriptedProcessor for webhook processing, and Connection Aliases for credential management.
Sourdough: ServiceNow Monitoring and Analytics
A Chrome extension for ServiceNow Admins and Developers with essential tools, analytics, graphs and monitoring features.
Free to install. Pro $5/month after a 14-day no-card trial.
Pro requires the ServiceNow admin role. Upgrade inside the extension.
Implementation Steps
Create Cloudflare API token and store credentials in ServiceNow
Navigate to your Cloudflare dashboard and go to My Profile > API Tokens to create a custom token with Zone:Read, Zone.Zone:Read, and Zone.Analytics:Read permissions for all zones or specific zones you want to monitor. Copy the generated token immediately as it won't be displayed again. In ServiceNow, navigate to Connections & Credentials > Credentials and create a new Basic Auth credential with the username field set to 'Bearer' and the password field containing your Cloudflare API token. Set the name to 'Cloudflare API Token' and ensure the credential is active before saving.
Configure Connection Alias for Cloudflare API endpoints
Navigate to Connections & Credentials > Connection & Credential Aliases in ServiceNow and create a new alias named 'Cloudflare API Connection'. Set the connection URL to 'https://api.cloudflare.com/client/v4' and associate it with the Cloudflare API Token credential created in the previous step. Configure the alias to use HTTPS protocol and set the timeout to 30 seconds to handle potential API latency. Test the connection using the Test Connection feature to verify authentication is working correctly before proceeding.
Create Scripted REST API to receive Cloudflare webhooks
Navigate to System Web Services > Scripted Web Services > Scripted REST APIs and create a new API with the name 'Cloudflare Webhook Handler' and API ID 'cloudflare_webhooks'. Create a POST resource with the resource path '/security_event' and set it to require authentication using basic auth or API key validation. Configure the resource to accept JSON content and set up proper error handling for malformed payloads. Add rate limiting configuration to prevent webhook flooding and ensure the API endpoint is accessible from external systems by configuring appropriate ACL rules.
(function process(request, response) {
try {
var payload = request.body.data;
var eventType = payload.outcome || 'unknown';
// Create incident for security events
var incident = new GlideRecord('incident');
incident.initialize();
incident.short_description = 'Cloudflare Security Event: ' + eventType;
incident.description = 'Event details: ' + JSON.stringify(payload);
incident.category = 'Security';
incident.subcategory = 'Web Application Firewall';
incident.priority = payload.action === 'block' ? 2 : 4;
incident.caller_id = gs.getProperty('cloudflare.default_caller');
var incidentSysId = incident.insert();
response.setStatus(200);
response.getWriter().print(JSON.stringify({status: 'success', incident: incidentSysId}));
} catch (e) {
response.setStatus(500);
response.getWriter().print(JSON.stringify({error: e.message}));
gs.error('Cloudflare webhook processing error: ' + e.message);
}
})(request, response);Configure outbound REST message for Cloudflare API calls
Navigate to System Web Services > Outbound > REST Message and create a new REST message named 'Cloudflare API Client'. Set the endpoint to reference the Connection Alias created earlier using the format '${cloudflare_api_connection}' and configure the default HTTP headers including 'Content-Type: application/json' and 'Accept: application/json'. Create multiple HTTP methods including GET for zones, GET for analytics, and POST for DNS record updates, each with appropriate relative paths like '/zones', '/zones/{zone_id}/analytics/dashboard', and '/zones/{zone_id}/dns_records'. Configure variable substitutions for zone IDs and other dynamic parameters, and set up proper error handling for HTTP status codes including rate limiting responses.
// Example function to get Cloudflare zones
function getCloudflareZones() {
try {
var request = new sn_ws.RESTMessageV2('Cloudflare API Client', 'get zones');
var response = request.execute();
if (response.getStatusCode() === 200) {
var zones = JSON.parse(response.getBody());
return zones.result;
} else if (response.getStatusCode() === 429) {
gs.warn('Cloudflare API rate limit exceeded');
return null;
} else {
gs.error('Cloudflare API error: ' + response.getStatusCode() + ' - ' + response.getBody());
return null;
}
} catch (e) {
gs.error('Error calling Cloudflare API: ' + e.message);
return null;
}
}Create CMDB CI class for Cloudflare zones and DNS records
Navigate to Configuration > CI Class Manager and create a new CI class extending from 'Network Gear' or 'Application' called 'Cloudflare Zone'. Add custom attributes including zone_id, zone_name, zone_status, name_servers (string list), and security_level to track essential Cloudflare zone properties. Create a second CI class called 'Cloudflare DNS Record' with attributes for record_type, record_name, record_content, ttl, and proxied status. Configure discovery relationships between zones and DNS records using the 'Contains::Contained by' relationship type, and set up appropriate CI identification rules based on zone_id and record identifiers.
Build scheduled job for CMDB synchronization
Navigate to System Definition > Scheduled Jobs and create a new scheduled job named 'Cloudflare CMDB Sync' that runs daily to synchronize zone and DNS record data. Configure the job to use the REST message created earlier to fetch all zones, then iterate through each zone to retrieve DNS records and analytics data. Implement proper error handling and logging to track sync success rates and API quota usage. Set up the job to create, update, or mark as deleted CI records based on the current state in Cloudflare, ensuring data consistency between systems while respecting API rate limits.
// Scheduled job script for CMDB sync
var CloudflareSync = {
syncZones: function() {
var zones = this.getCloudflareZones();
if (!zones) return;
for (var i = 0; i < zones.length; i++) {
var zone = zones[i];
var zoneCi = new GlideRecord('u_cloudflare_zone');
zoneCi.addQuery('u_zone_id', zone.id);
zoneCi.query();
if (zoneCi.next()) {
// Update existing zone
zoneCi.u_zone_status = zone.status;
zoneCi.u_name_servers = zone.name_servers.join(',');
zoneCi.update();
} else {
// Create new zone CI
zoneCi.initialize();
zoneCi.u_zone_id = zone.id;
zoneCi.u_zone_name = zone.name;
zoneCi.u_zone_status = zone.status;
zoneCi.name = 'Cloudflare Zone: ' + zone.name;
zoneCi.insert();
}
// Sync DNS records for this zone
this.syncDnsRecords(zone.id, zoneCi.sys_id);
}
},
getCloudflareZones: function() {
// Implementation from previous step
}
};
CloudflareSync.syncZones();Configure webhook subscriptions in Cloudflare
Access your Cloudflare dashboard and navigate to the Notifications section under your account profile to set up webhook notifications for security events. Create webhook endpoints pointing to your ServiceNow Scripted REST API URL (https://your-instance.service-now.com/api/your-namespace/cloudflare_webhooks/security_event) and configure authentication if required. Subscribe to relevant event types including Firewall Events, DDoS Attack Alerts, Rate Limiting triggers, and SSL/TLS certificate expiration warnings. Test each webhook subscription using Cloudflare's test notification feature to ensure events are properly received and processed by ServiceNow.
Test integration and validate incident creation
Trigger test security events in Cloudflare by temporarily creating restrictive WAF rules or using the webhook test functionality to simulate DDoS alerts and firewall blocks. Verify that incidents are automatically created in ServiceNow with appropriate priority levels, categorization, and detailed event information in the description field. Check the System Logs > Events and System Logs > REST to confirm webhook payloads are being received and processed correctly. Run the CMDB synchronization job manually to verify zone and DNS record data is being imported accurately, then validate that scheduled job execution completes successfully with proper error handling for API failures.
// Test script to validate Cloudflare integration
var testIntegration = function() {
// Test outbound API connectivity
var zones = getCloudflareZones();
if (zones && zones.length > 0) {
gs.info('Successfully retrieved ' + zones.length + ' zones from Cloudflare API');
} else {
gs.error('Failed to retrieve zones from Cloudflare API');
return false;
}
// Verify webhook endpoint is accessible
var testPayload = {
outcome: 'block',
action: 'block',
source: 'firewallrules',
description: 'Integration test event'
};
// Check if recent incidents were created from webhooks
var recentIncidents = new GlideRecord('incident');
recentIncidents.addQuery('short_description', 'STARTSWITH', 'Cloudflare Security Event');
recentIncidents.addQuery('sys_created_on', '>', gs.hoursAgo(1));
recentIncidents.query();
gs.info('Found ' + recentIncidents.getRowCount() + ' recent Cloudflare incidents');
return true;
};
testIntegration();Common Use Cases
Automated security incident creation from WAF violations
When Cloudflare's Web Application Firewall blocks malicious requests or detects attack patterns, webhooks automatically trigger incident creation in ServiceNow with severity based on the threat level. The incidents include detailed payload information, source IP addresses, attack vectors, and affected zones, enabling security teams to investigate and respond quickly. Integration with ServiceNow's Security Incident Response application allows for automatic assignment to appropriate security analysts based on attack type and geographic location of threats.
DDoS attack monitoring and response coordination
Large-scale DDoS attacks detected by Cloudflare trigger high-priority incidents in ServiceNow with automatic escalation to network operations teams and executive stakeholders. The integration captures attack metrics including request volume, duration, and mitigation status, while creating related tasks for infrastructure assessment and customer communication. ServiceNow's Major Incident Management process is automatically initiated for attacks exceeding defined thresholds, ensuring coordinated response and proper documentation.
SSL certificate lifecycle management
Cloudflare certificate expiration notifications create ServiceNow change requests for certificate renewal with automatic assignment to appropriate technical teams based on domain ownership. The integration tracks certificate validity periods, renewal status, and dependencies on other systems to prevent service disruptions. Integration with ServiceNow's Certificate Management application provides centralized visibility across all Cloudflare-managed certificates and automated renewal workflows.
DNS zone configuration management in CMDB
Scheduled synchronization jobs maintain accurate CMDB records for all Cloudflare-managed DNS zones, including zone status, name servers, security settings, and DNS record details. This enables impact analysis during outages, change management for DNS modifications, and compliance reporting for domain management policies. The CMDB integration supports automated discovery relationships between zones, DNS records, and dependent applications or services.
Performance degradation alerting and incident correlation
Cloudflare analytics data indicating performance issues or unusual traffic patterns triggers proactive incidents in ServiceNow before user complaints arise. The integration correlates Cloudflare metrics with other monitoring tools to provide comprehensive incident context and enable faster root cause analysis. Automated enrichment of incidents with historical performance data and related configuration changes helps technical teams identify patterns and implement preventive measures.
Troubleshooting
Webhook payloads received but incidents not created with error 'Cannot read property of undefined'
Check the Scripted REST API logs under System Logs > REST to identify which property is missing from the webhook payload. Cloudflare webhook structures vary by event type, so add null checks and default values for optional properties. Modify your processing script to handle different payload schemas gracefully, and consider logging the full payload structure during development to understand variations in event data.
Cloudflare API calls returning 429 Too Many Requests errors during CMDB sync
Implement exponential backoff logic in your scheduled job with delays between API calls, as Cloudflare limits requests to 1,200 per 5-minute window. Add retry mechanisms with increasing delays (1s, 5s, 15s) and consider splitting large zone synchronization jobs into smaller batches. Monitor your API usage in the Cloudflare dashboard and adjust sync frequency to stay within rate limits while maintaining data freshness.
Connection alias test fails with SSL handshake errors or timeout
Verify that your ServiceNow instance can reach api.cloudflare.com on port 443 by checking network connectivity and firewall rules. If using a MID Server unnecessarily, switch to direct HTTPS connections as Cloudflare API doesn't require internal network access. Check your instance's outbound HTTP log for detailed SSL error messages and ensure your ServiceNow instance's SSL certificate store includes current root certificates for Cloudflare's CDN.
Scheduled CMDB sync job fails with 'Invalid API token' error after working previously
Check if your Cloudflare API token has expired or had its permissions modified in the Cloudflare dashboard under API Tokens. Verify that the token still has the required Zone:Read permissions and hasn't been inadvertently rotated or deactivated. Update the ServiceNow credential record with a new token if necessary, and consider implementing token validation checks in your sync script to detect expiration before job failure.
High-priority incidents created for every minor WAF block causing alert fatigue
Refine your incident creation logic to differentiate between routine WAF blocks and genuine security threats by analyzing attack patterns, source reputation, and payload characteristics. Implement severity classification based on factors like attack volume, target sensitivity, and geographical origin. Consider aggregating low-severity events into summary incidents or using ServiceNow's Event Management for correlation before creating incidents.
CMDB CI records showing duplicate zones or DNS records after sync jobs
Review your CI identification rules to ensure unique matching on zone_id and record identifiers rather than names which might change. Check that your sync job logic properly queries existing records before creating new ones, and implement proper error handling for Cloudflare API pagination. Add logging to track CI creation and updates, and consider implementing a cleanup process to remove orphaned records from deleted zones.
Pro Tips
- →Implement event correlation logic to group related Cloudflare security events into single incidents, reducing noise while maintaining visibility into attack patterns and trends. Use ServiceNow's Event Management rules to aggregate multiple WAF violations from the same source IP or targeting the same zone within a time window.
- →Configure custom business rules to automatically attach Cloudflare analytics dashboards and security reports as incident attachments, providing responders with immediate context about traffic patterns and threat intelligence. This reduces investigation time and improves incident response quality.
- →Set up ServiceNow's Performance Analytics to track key metrics from Cloudflare integrations, including incident creation rates, API response times, and webhook processing success rates. Create executive dashboards showing security event trends and integration health for stakeholder reporting.
- →Use ServiceNow's Transform Maps when processing webhook payloads to standardize field mappings and enable easier maintenance when Cloudflare changes their payload structure. This approach provides better error handling and allows for field validation before record creation.
- →Implement circuit breaker patterns in your API integration code to automatically disable polling when Cloudflare API errors exceed thresholds, preventing cascade failures and reducing unnecessary API quota consumption during Cloudflare service disruptions.
- →Configure ServiceNow's Notification system to alert integration administrators when webhook endpoints are unreachable or API authentication fails, ensuring rapid response to integration failures that could impact security monitoring coverage.
Known Limitations
- —Cloudflare's webhook notifications have a retry limit of 3 attempts with exponential backoff, meaning temporary ServiceNow outages can result in missed security events that won't be retried after the retry window expires. Consider implementing a backup polling mechanism for critical security events during maintenance windows.
- —The Cloudflare API rate limit of 1,200 requests per 5-minute window can be restrictive for large organizations with many zones, requiring careful optimization of CMDB synchronization jobs and potential data freshness trade-offs. Enterprise customers may have higher limits but should still implement proper rate limiting logic.
- —Webhook payload sizes are limited to 1MB, which may truncate detailed security event data for large-scale attacks or complex WAF rule violations, potentially losing forensic details needed for thorough incident investigation. Consider supplementing webhook data with API calls for detailed event information.
- —ServiceNow's Scripted REST API framework doesn't provide built-in webhook signature verification for Cloudflare notifications, requiring custom implementation of HMAC validation to ensure webhook authenticity and prevent spoofed security events from creating false incidents.
- —Real-time synchronization of DNS record changes isn't supported through webhooks, requiring polling-based CMDB updates that may have delays of several minutes to hours depending on sync job frequency, potentially impacting change management accuracy during rapid DNS modifications.
Frequently Asked Questions
Can I use ServiceNow's Integration Hub spoke for Cloudflare instead of custom REST integration?
Currently, there is no official Cloudflare spoke available in ServiceNow's Integration Hub, requiring custom implementation using Scripted REST APIs and REST Message records. While this requires more development effort, it provides greater flexibility in handling Cloudflare's diverse API endpoints and webhook payload structures. Monitor the ServiceNow Store for potential third-party spokes or official ServiceNow releases that might simplify the integration in future releases.
How can I ensure webhook security and prevent unauthorized incident creation?
Implement webhook signature verification by configuring HMAC validation in your Scripted REST API using Cloudflare's webhook signing secret, which can be found in your Cloudflare notification settings. Additionally, use ServiceNow's built-in API authentication mechanisms and consider IP allow-listing for Cloudflare's webhook source IP ranges. Store webhook secrets in ServiceNow's encrypted credential store and implement request logging to detect potential abuse or unauthorized access attempts.
What's the best way to handle Cloudflare API pagination for large zone inventories?
Implement recursive API calls using the 'result_info' metadata returned by Cloudflare API responses, which includes pagination details like page count and total results. Use GlideRecord batch processing to handle large datasets efficiently and implement proper error handling for timeout scenarios. Consider breaking large synchronization jobs into smaller chunks and using ServiceNow's scheduled job chaining to process paginated results across multiple execution windows while respecting API rate limits.
How do I correlate Cloudflare incidents with other security tools in ServiceNow?
Use ServiceNow's Event Management correlation rules to match Cloudflare incidents with events from other security tools based on common attributes like source IP, attack signatures, or time windows. Implement custom correlation logic in Business Rules that check for related security incidents across different data sources and automatically link them using the Related Records feature. Consider using ServiceNow's Security Incident Response application for advanced threat correlation and automated playbook execution.
Can I trigger Cloudflare actions from ServiceNow incidents and change requests?
Yes, you can implement bidirectional integration by creating ServiceNow Flow Designer actions that call Cloudflare APIs to update security rules, DNS records, or firewall configurations based on incident resolution or approved change requests. Use RESTMessageV2 calls within Business Rules or Flow Designer to automate responses like IP blocking, DNS record updates, or security level adjustments. Ensure proper approval workflows and change management processes are in place before implementing automated configuration changes.
What ServiceNow modules and plugins are required for full Cloudflare integration functionality?
The core integration requires the base ServiceNow platform with Event Management and IT Service Management plugins activated for incident and change management. Configuration Management Database (CMDB) plugin is essential for zone and DNS record tracking, while Security Incident Response provides advanced security event correlation capabilities. Integration Hub Professional license enables advanced webhook processing and flow-based automation, though basic functionality can work with standard platform capabilities.
How do I handle Cloudflare zone transfers and ownership changes in ServiceNow CMDB?
Implement lifecycle management rules in your CMDB synchronization job that detect zone status changes and ownership transfers by monitoring zone metadata changes between sync cycles. Create automated workflows that retire old CI records when zones are transferred out and establish new relationships when zones are transferred in. Use ServiceNow's Discovery and Service Mapping capabilities to automatically update dependencies and relationships affected by zone ownership changes, ensuring accurate impact analysis and change management processes.
Test Your Knowledge
Quick 3-question quiz — see how your ServiceNow skills stack up.
A list view on a table with millions of records is slow. Best fix?
Select an answer to continue