ServiceNow Bitbucket integration enables automated change management workflows by connecting your Git repository activities with ITSM processes, solving the critical business problem of maintaining governance and approval gates in DevOps pipelines while ensuring deployment visibility for IT operations teams. This integration is primarily used by DevOps engineers, release managers, and IT operations teams who need to enforce change control processes without slowing down development velocity. The integration supports bi-directional data flows where Bitbucket webhook events trigger ServiceNow Flow Designer workflows to create or update Change Requests, while ServiceNow can query Bitbucket REST APIs to retrieve pull request details and deployment status. The primary automation pattern uses inbound webhook processing combined with outbound REST calls, implemented through ServiceNow's Scripted REST API framework and Integration Hub flows within the IT Service Management and DevOps modules.
Prerequisites
- •ServiceNow Tokyo release or later with Integration Hub Professional license
- •Bitbucket Data Center 7.0+ or Bitbucket Cloud workspace with admin permissions
- •Flow Designer activated and configured in ServiceNow instance
- •Change Management plugin (com.snc.change_management) activated
- •DevOps Insights plugin (com.snc.devops.insights) recommended but not required
- •Network connectivity allowing inbound HTTPS traffic to ServiceNow instance
- •Bitbucket App Password or Personal Access Token with repository and webhook permissions
Architecture Overview
This integration uses ServiceNow's native REST capabilities without requiring a dedicated Integration Hub spoke, leveraging Scripted REST APIs to receive Bitbucket webhooks and RESTMessageV2 records for outbound API calls to Bitbucket. Authentication is established using Basic Authentication with Bitbucket App Passwords stored in ServiceNow Connection & Credential records, providing secure credential management and rotation capabilities. Data flows bidirectionally with Bitbucket webhooks triggering inbound events to create Change Requests, while ServiceNow makes outbound calls to retrieve pull request metadata and update deployment pipeline status based on change approval states. No MID Server is required as all communication occurs over HTTPS using ServiceNow's built-in REST framework, though firewall rules must allow inbound traffic to the ServiceNow instance for webhook delivery. API rate limiting follows Bitbucket's standard limits of 1000 requests per hour for Data Center and 1000 requests per hour per user for Cloud, with built-in retry logic recommended for production implementations.
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 Bitbucket App Password and ServiceNow Connection Credential
In Bitbucket, navigate to Personal Settings > App Passwords and create a new App Password with Repositories:Read, Webhooks:Read/Write, and Pull Requests:Read permissions, then copy the generated password immediately as it cannot be viewed again. In ServiceNow, navigate to Connections & Credentials > Credentials and create a new Basic Auth Credential with your Bitbucket username and the App Password as the password field. Set the credential name to 'Bitbucket_Integration_Cred' and ensure the credential is available to the global scope. Test the credential by creating a simple REST Message to Bitbucket's user API endpoint to verify authentication is working properly.
// Test credential with basic API call
var rm = new RESTMessage('BitbucketTest', 'GET');
rm.setEndpoint('https://api.bitbucket.org/2.0/user');
rm.setBasicAuth('your_username', 'app_password');
var response = rm.execute();
gs.info('Bitbucket Auth Test Status: ' + response.getStatusCode());Create ServiceNow Scripted REST API for Webhook Reception
Navigate to System Web Services > Scripted Web Services > Scripted REST APIs and create a new API resource called 'Bitbucket Webhooks' with base path '/bitbucket/v1'. Create a POST resource called 'webhook_handler' that will process incoming webhook payloads from Bitbucket. Configure the resource to accept JSON content and implement proper error handling for malformed payloads. Set the security to require a valid ServiceNow user session or implement API key validation to prevent unauthorized webhook calls from reaching your endpoint.
(function process(request, response) {
try {
var payload = JSON.parse(request.body.dataString);
var eventType = request.headers['x-event-key'];
gs.info('Received Bitbucket webhook: ' + eventType);
if (eventType === 'pullrequest:created' || eventType === 'pullrequest:updated') {
sn_flow_trigger.FlowTriggerAPI.fireTrigger('bitbucket_pr_trigger', payload);
}
response.setStatus(200);
response.setBody('Webhook processed successfully');
} catch (e) {
gs.error('Bitbucket webhook processing error: ' + e.message);
response.setStatus(400);
response.setBody('Invalid webhook payload');
}
})(request, response);Configure Bitbucket Webhook to Call ServiceNow
In your Bitbucket repository, navigate to Repository Settings > Webhooks and create a new webhook pointing to your ServiceNow instance endpoint in the format 'https://your-instance.service-now.com/api/snc/bitbucket/v1/webhook_handler'. Select the specific events you want to trigger ServiceNow workflows, typically Pull Request Created, Updated, Merged, and Declined events. Configure the webhook to send JSON payloads and set up a secret token if you implemented webhook signature verification in your Scripted REST API. Test the webhook using Bitbucket's built-in test feature to ensure connectivity and proper payload delivery to ServiceNow.
Create Flow Designer Trigger for Bitbucket Events
Navigate to Process Automation > Flow Designer and create a new Flow Trigger called 'Bitbucket PR Trigger' with trigger name 'bitbucket_pr_trigger' that matches the trigger fired in your Scripted REST API. Configure the trigger to accept the Bitbucket webhook payload as input data, defining key fields like repository name, pull request ID, source and target branches, and author information. Set up proper data validation in the trigger conditions to ensure only valid payloads proceed to the flow execution. Test the trigger by manually firing it with sample Bitbucket payload data to verify the flow receives and processes the webhook data correctly.
// Sample trigger condition script
(function() {
var payload = trigger.bitbucket_payload;
// Only process pull requests targeting main/master branches
if (payload && payload.pullrequest && payload.pullrequest.destination) {
var targetBranch = payload.pullrequest.destination.branch.name;
return (targetBranch === 'main' || targetBranch === 'master');
}
return false;
})();Build Flow to Create Change Requests from Pull Requests
In Flow Designer, create a new flow called 'Bitbucket PR to Change Request' that activates on your Bitbucket trigger. Add a 'Create Record' action to create a new Change Request record, mapping Bitbucket pull request data to Change Request fields like short description, description, and implementation plan. Configure the Change Request type as 'Standard' or 'Normal' based on your organization's change management process. Add conditional logic to handle different pull request actions (created vs updated vs merged) and set appropriate Change Request states and approval requirements based on the target branch and repository criticality.
// Flow script for mapping PR data to Change Request
var changeGr = new GlideRecord('change_request');
changeGr.initialize();
changeGr.type = 'standard';
changeGr.short_description = 'PR #' + inputs.pullrequest.id + ': ' + inputs.pullrequest.title;
changeGr.description = 'Pull Request: ' + inputs.pullrequest.links.html.href + '\nAuthor: ' + inputs.pullrequest.author.display_name;
changeGr.implementation_plan = inputs.pullrequest.description || 'See pull request for details';
changeGr.u_repository = inputs.repository.full_name;
changeGr.u_pr_id = inputs.pullrequest.id.toString();
changeGr.insert();
outputs.change_sys_id = changeGr.getUniqueValue();Create REST Message for Bitbucket API Calls
Navigate to System Web Services > Outbound > REST Message and create a new REST Message called 'Bitbucket API' with endpoint URL 'https://api.bitbucket.org/2.0' for Bitbucket Cloud or your Data Center URL. Create HTTP methods for common operations like 'Get Pull Request', 'Update Pull Request Status', and 'Get Repository Info', each configured with appropriate HTTP headers including Content-Type and Authorization using your stored credential. Configure variable substitution for dynamic values like repository name and pull request ID in the endpoint URLs. Test each HTTP method with real repository data to ensure proper authentication and response handling.
// REST Message HTTP Method for updating PR status
var rm = new RESTMessage('Bitbucket API', 'Update PR Status');
rm.setStringParameterNoEscape('repo_name', repository_full_name);
rm.setStringParameterNoEscape('pr_id', pull_request_id);
rm.setStringParameterNoEscape('status_key', 'INPROGRESS');
rm.setRequestBody(JSON.stringify({
'state': 'INPROGRESS',
'key': 'servicenow.change.approval',
'name': 'ServiceNow Change Approval',
'url': 'https://instance.service-now.com/change_request.do?sys_id=' + change_sys_id,
'description': 'Change Request approval pending'
}));
var response = rm.execute();
return response.getStatusCode();Implement Change Request Approval Gate Logic
Create a Business Rule on the Change Request table that triggers on state changes to 'Approved' or 'Rejected' and calls Bitbucket APIs to update pull request status accordingly. Configure the business rule to run 'After' update operations and add conditions to only process Change Requests that have associated pull request IDs in your custom field. Implement error handling for API call failures and add logging to track approval status synchronization between ServiceNow and Bitbucket. Add a second Business Rule or Flow that prevents pull request merges by updating Bitbucket branch permissions when Change Requests are in pending approval states.
// Business Rule: Update Bitbucket PR status on Change approval
(function executeRule(current, previous) {
if (current.state == '3' && current.u_pr_id) { // Authorized state
var rm = new RESTMessage('Bitbucket API', 'Update PR Status');
rm.setStringParameterNoEscape('repo_name', current.u_repository.toString());
rm.setStringParameterNoEscape('pr_id', current.u_pr_id.toString());
rm.setRequestBody(JSON.stringify({
'state': 'SUCCESSFUL',
'key': 'servicenow.change.approved',
'name': 'ServiceNow Change Approved',
'url': gs.getProperty('glide.servlet.uri') + 'change_request.do?sys_id=' + current.getUniqueValue()
}));
var response = rm.executeAsync();
gs.info('Updated Bitbucket PR status for Change: ' + current.number);
}
})(current, previous);Test End-to-End Integration and Configure Monitoring
Create a test pull request in your Bitbucket repository targeting the main branch to verify the complete workflow from webhook reception to Change Request creation. Monitor the System Logs > Events and REST Message logs to confirm webhook payloads are processed correctly and outbound API calls to Bitbucket are successful. Set up Integration Hub dashboards or create custom reports to track integration metrics like webhook processing times, failed API calls, and Change Request to Pull Request mapping accuracy. Configure email notifications or ITSM event management integration to alert administrators when the integration encounters errors or when critical pull requests are blocked pending change approvals.
// Monitor script for integration health checks
var integrationHealth = new GlideRecord('u_bitbucket_integration_log');
integrationHealth.addQuery('created', '>=', gs.daysAgo(1));
integrationHealth.addQuery('status', 'failed');
integrationHealth.query();
if (integrationHealth.getRowCount() > 5) {
gs.eventQueue('bitbucket.integration.failure.threshold', null,
'Integration failure count exceeded: ' + integrationHealth.getRowCount() + ' failures in 24 hours',
gs.getUserID());
}
gs.info('Bitbucket integration health check completed');Common Use Cases
Automated Change Request Creation for Production Deployments
When developers create pull requests targeting production or main branches, the integration automatically generates Standard Change Requests in ServiceNow with pre-populated implementation details from the pull request description. The Change Request includes links back to the Bitbucket pull request, affected repository information, and maps the developer as the change implementer. This use case ensures all production changes follow ITIL change management processes while maintaining development velocity by eliminating manual Change Request creation.
Deployment Pipeline Approval Gates
Pull requests remain blocked from merging until their associated ServiceNow Change Requests receive proper approvals from change advisory board members or automated approval workflows. The integration updates Bitbucket pull request status checks and branch protection rules based on ServiceNow change approval states, preventing unauthorized production deployments. This provides governance oversight for critical system changes while giving clear visibility to developers about approval status and requirements.
Emergency Change Fast-Track Processing
Pull requests labeled with 'emergency' or 'hotfix' tags trigger creation of Emergency Change Requests with expedited approval workflows and automatic notifications to on-call change managers. The integration monitors emergency change timelines and automatically escalates to change management leadership if approval SLAs are at risk. This ensures critical production fixes can be deployed rapidly while maintaining audit trails and proper emergency change documentation.
Post-Deployment Change Closure Automation
When pull requests are successfully merged and deployment pipelines complete, the integration automatically updates associated Change Requests to 'Review' status and schedules Post Implementation Review tasks. Integration with monitoring tools can also update change records with deployment success metrics and automatically close changes that meet success criteria. This reduces manual change lifecycle management overhead while ensuring proper change closure documentation and review processes.
Compliance Audit Trail Generation
The integration maintains bidirectional linking between code changes and change management records, creating comprehensive audit trails that map every production deployment to approved change requests with proper authorization. Change Request records include complete pull request metadata, approval timestamps, and deployment verification results, supporting SOX compliance and regulatory audit requirements. This automated documentation significantly reduces compliance preparation effort while ensuring complete change traceability for auditors.
Troubleshooting
Bitbucket webhooks return 401 Unauthorized errors when calling ServiceNow
Check the Scripted REST API security settings and ensure the webhook endpoint either allows anonymous access with proper API key validation or configure Bitbucket to authenticate with a valid ServiceNow user credential. Navigate to System Logs > REST to examine the exact authentication failure details and verify network connectivity from Bitbucket servers to your ServiceNow instance. If using IP restrictions, whitelist Bitbucket's webhook IP ranges in your ServiceNow instance security policies.
Change Requests are created but Bitbucket pull request status updates fail with 403 Forbidden
Verify your Bitbucket App Password or Personal Access Token has sufficient permissions for the target repository, particularly Pull Requests:Write permissions for status updates and Webhooks:Write for branch protection modifications. Check the outbound REST message logs in ServiceNow under System Logs > Outbound HTTP Requests to see the exact error response from Bitbucket API. Ensure the credential stored in ServiceNow matches an active Bitbucket user with appropriate repository permissions and hasn't expired or been revoked.
Flow triggers fire multiple times for single Bitbucket webhook events
Implement idempotency checks in your Flow Designer trigger conditions by tracking processed webhook IDs in a custom table or using Bitbucket's event UUID headers to prevent duplicate processing. Add logging to identify whether multiple webhooks are being sent by Bitbucket or if ServiceNow is processing the same webhook multiple times due to retry logic. Consider adding a brief delay in your flow execution or implementing webhook queuing to handle rapid-fire events from batch operations.
Pull request metadata is incomplete or missing in ServiceNow Change Requests
Review the Bitbucket webhook payload structure in the System Logs to ensure all required fields are present in the incoming data and update your Flow Designer field mappings accordingly. Different Bitbucket events may have varying payload structures, so implement conditional field mapping logic that handles optional fields gracefully. Test with different types of pull request operations (create, update, merge) to ensure your field extraction logic works consistently across all webhook event types.
High latency between pull request actions and Change Request updates
Check ServiceNow scheduled job queues and Flow Designer execution logs to identify bottlenecks in webhook processing or outbound API calls to Bitbucket. Consider implementing asynchronous processing for complex change management workflows to prevent webhook timeouts and improve response times. Monitor Integration Hub license usage and flow execution quotas as license limits can introduce processing delays during peak usage periods.
Webhook delivery fails intermittently with network timeout errors
Configure webhook retry logic in Bitbucket and implement proper timeout handling in your ServiceNow Scripted REST API endpoint to gracefully handle temporary network issues. Check ServiceNow instance performance during webhook failures to rule out system resource constraints affecting inbound request processing. Consider implementing a webhook status monitoring dashboard that tracks delivery success rates and automatically alerts administrators when failure rates exceed acceptable thresholds.
Pro Tips
- →Implement webhook signature verification using HMAC-SHA256 to ensure webhook authenticity and prevent malicious payload injection, storing the webhook secret in ServiceNow's encrypted credential store. This adds crucial security validation that protects against unauthorized webhook calls that could create fraudulent Change Requests or bypass approval processes.
- →Create custom Change Request types specifically for different repository tiers (critical production vs development) with tailored approval workflows and SLA timers that automatically escalate based on system criticality. This ensures high-risk changes receive appropriate oversight while allowing faster processing for lower-risk development environment changes.
- →Use ServiceNow's Event Management integration to correlate deployment failures with Change Requests, automatically updating change status and creating incident records when monitoring tools detect post-deployment issues. This creates a closed-loop feedback system that improves change success tracking and incident response times.
- →Implement batch processing for bulk pull request operations by queuing webhook events and processing them in scheduled jobs rather than real-time Flow execution, preventing Integration Hub license exhaustion during large merge operations. This approach also allows for better error handling and retry logic for failed Change Request creations.
- →Configure conditional approval workflows that automatically approve certain types of changes (like documentation updates or non-production deployments) while requiring manual approval for database schema changes or configuration modifications. Use Bitbucket file path analysis in the webhook payload to determine change risk levels and route approvals accordingly.
- →Set up Integration Hub dashboards with key performance indicators tracking webhook processing times, Change Request approval duration, and deployment success rates to identify bottlenecks and optimization opportunities. Include automated reporting for change management leadership showing compliance metrics and process efficiency trends.
Known Limitations
- —Bitbucket Cloud API rate limiting restricts requests to 1000 per hour per user, which may be insufficient for organizations with high-volume repository activity or complex webhook processing workflows. Large-scale implementations may require multiple API credentials or careful request batching to avoid hitting rate limits during peak development periods.
- —ServiceNow Integration Hub Professional license limits on flow executions may constrain the number of webhook events that can be processed per month, particularly for organizations with numerous repositories and active development teams. Exceeding license limits will pause flow execution until the next billing cycle, potentially blocking critical change management workflows.
- —Real-time webhook processing can introduce latency in Change Request creation and approval workflows, particularly during high-traffic periods when ServiceNow instance performance degrades or when complex approval routing is required. Network connectivity issues between Bitbucket and ServiceNow can also cause webhook delivery delays or failures that impact deployment timelines.
Frequently Asked Questions
Can this integration work with Bitbucket Data Center on-premises installations?
Yes, the integration supports both Bitbucket Cloud and Data Center installations with minimal configuration changes, primarily requiring different API endpoint URLs and potentially different authentication methods depending on your Data Center setup. For Data Center implementations, you may need to configure network firewall rules to allow webhook traffic from your Bitbucket servers to reach ServiceNow, and authentication typically uses the same App Password mechanism unless you've implemented custom authentication providers. The webhook payload structures are identical between Cloud and Data Center versions, so Flow Designer configurations remain the same.
How can I customize Change Request types and approval workflows for different repositories?
You can implement conditional logic in your Flow Designer workflows that examines the repository name or webhook payload metadata to determine appropriate Change Request types and approval routing. Create multiple Flow Designer flows activated by the same webhook trigger but with different conditions based on repository patterns or custom Bitbucket repository properties. Consider using ServiceNow's Approval Workflow Engine with custom approval rules that map repository criticality levels to different change advisory board members or automated approval criteria based on change risk assessment.
What happens if ServiceNow is unavailable when Bitbucket sends webhooks?
Bitbucket automatically retries failed webhook deliveries using exponential backoff for up to 24 hours, but webhooks that fail beyond this window are permanently lost and require manual intervention to create missing Change Requests. Implement monitoring dashboards that track webhook delivery success rates and configure alerting when failure rates exceed thresholds, allowing administrators to identify and remediate missing change records. Consider implementing a backup webhook endpoint or developing reconciliation scripts that can compare Bitbucket pull request activity with ServiceNow Change Request records to identify and correct synchronization gaps.
Can I integrate with multiple Bitbucket workspaces or organizations simultaneously?
Yes, you can configure multiple credential sets and webhook endpoints to support multiple Bitbucket organizations, either by creating separate Scripted REST API resources for each organization or implementing routing logic within a single webhook handler that processes payloads differently based on organization context. Each organization should use distinct App Passwords stored as separate ServiceNow credentials, and your Flow Designer workflows can include conditional logic to apply different change management processes based on the source organization. This approach scales well for managed service providers or large enterprises with multiple development organizations requiring integrated change management.
How do I handle pull request updates and synchronize changes with existing Change Requests?
Implement update logic in your Flow Designer workflows that queries for existing Change Requests using the stored pull request ID field and updates relevant fields rather than creating duplicate records when processing 'pullrequest:updated' webhook events. Use GlideRecord operations to modify Change Request descriptions, implementation plans, or other fields when pull requests are updated with new commits or description changes. Consider creating Change Request work notes or comments that track the update history from Bitbucket, providing change implementers with complete visibility into the evolution of the change scope and implementation approach throughout the development process.
Is it possible to prevent pull request merges until Change Request approval without using branch protection rules?
Yes, you can implement pull request status checks through Bitbucket's commit status API, which creates required status checks that prevent merging until marked as successful by ServiceNow approval workflows. This approach uses the Bitbucket Build Status API to create custom status contexts like 'servicenow/change-approval' that remain in pending or failed states until Change Requests reach approved status. The status check approach is more flexible than branch protection rules as it can be applied selectively based on pull request content or target branch, and provides developers with clear visibility into approval status directly within the Bitbucket pull request interface.
What are the security considerations for exposing ServiceNow endpoints to Bitbucket webhooks?
Implement webhook signature verification using HMAC-SHA256 to validate that webhooks originate from your Bitbucket instance and haven't been tampered with during transmission, storing webhook secrets securely in ServiceNow encrypted credential records. Configure IP address restrictions on your ServiceNow instance to only allow webhook traffic from known Bitbucket server IP ranges, and implement rate limiting in your Scripted REST API endpoints to prevent potential denial-of-service attacks. Consider using API gateway solutions or reverse proxy configurations that can provide additional security layers, request validation, and logging before webhook payloads reach ServiceNow, particularly for high-security environments with strict network access controls.
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