Integrations

ServiceNow GitLab Integration Guide

intermediatePersonal Access Token in Authorization headerGitLab

The ServiceNow GitLab integration connects development workflows with IT service management by automating change management processes, creating incidents from GitLab alerts, and linking merge requests to ServiceNow change records. This integration is essential for organizations implementing DevOps practices while maintaining governance and compliance requirements through ServiceNow's ITSM processes. The integration enables bi-directional data flows where GitLab CI/CD pipelines can automatically create and update ServiceNow change requests, while ServiceNow can track deployment status and link code changes to business impact. The primary automation pattern uses webhook-based triggers from GitLab events combined with ServiceNow's REST API calls, implemented through Integration Hub's GitLab spoke or custom scripted REST APIs in the System Web Services module.

Prerequisites

  • ServiceNow San Diego release or later with Integration Hub Professional license
  • GitLab Premium or Ultimate tier with API access enabled
  • ServiceNow Change Management plugin (com.snc.change_management) activated
  • Administrator role in ServiceNow with rest_api_explorer and web_service_admin roles
  • GitLab Maintainer or Owner role with API token creation permissions
  • ServiceNow Event Management plugin for incident automation from GitLab alerts
  • MID Server configured if GitLab instance is behind firewall or on-premises

Architecture Overview

The integration uses ServiceNow's Integration Hub GitLab spoke (com.snc.integration.gitlab) which provides pre-built actions for common GitLab operations including merge request management and pipeline status retrieval. Authentication is established using GitLab personal access tokens stored in ServiceNow Connection & Credential Aliases under the Connections & Credentials application, with the credential alias referenced by Integration Hub flows and REST Message records. Data flows bi-directionally with GitLab webhook events triggering ServiceNow Scripted REST APIs for incident creation, while outbound Integration Hub flows call GitLab APIs to update merge request statuses and retrieve pipeline information. A MID Server is required only when GitLab instances are hosted on-premises or behind corporate firewalls that block direct ServiceNow cloud access. GitLab API rate limits allow 2000 requests per minute for authenticated users, which is sufficient for most enterprise integrations, but consider implementing request queuing for high-volume environments using ServiceNow's REST Message throttling capabilities.

Sourdough
Chrome Extension

Sourdough: ServiceNow Monitoring and Analytics

A Chrome extension for ServiceNow Admins and Developers with essential tools, analytics, graphs and monitoring features.

Instance HealthGraphs & ChartsAPI HealthDeveloper ToolsQuick SearchInstance Switcher
Add to Chrome

Free to install. Pro $5/month after a 14-day no-card trial.
Pro requires the ServiceNow admin role. Upgrade inside the extension.

Overview
Tasks
CMDB
API
Metrics
Monitor
Internals
Instance:sourdoughdev·Version:Yokohama
Instance StateONLINE
System StatusFully Operational
Session Timeout90 minutes
Logged-In Sessions2 (20 active)
Build Nameyokohama-12-18-2024_p1
IP Address10.159.128.43
Instance HealthHealth Score: 90%
🔥 5dSourdough (Chrome Plugin)Dark Mode

Implementation Steps

1

Create GitLab Personal Access Token and ServiceNow Credential

In GitLab, navigate to User Settings > Access Tokens and create a new personal access token with api, read_api, read_repository, and write_repository scopes, setting an appropriate expiration date for your security policies. Copy the generated token immediately as it won't be shown again. In ServiceNow, navigate to Connections & Credentials > Credentials and create a new Basic Auth credential with username as your GitLab username and password as the personal access token. Name the credential 'GitLab_API_Token' and ensure it's available for Integration Hub by checking the 'Available for Integration Hub' checkbox.

2

Configure GitLab Connection Alias in ServiceNow

Navigate to Connections & Credentials > Connection & Credential Aliases and create a new alias named 'GitLab_Connection'. Set the connection URL to your GitLab instance base URL (e.g., https://gitlab.example.com or https://gitlab.com) and associate it with the credential created in step 1. In the Connection section, specify the protocol as HTTPS and ensure the 'Ignore SSL Certificate Errors' is unchecked unless working with self-signed certificates. Test the connection by clicking the 'Test Connection' button to verify ServiceNow can reach your GitLab instance.

3

Install and Configure Integration Hub GitLab Spoke

Navigate to System Applications > All Available Applications > All and search for 'GitLab' to find the Integration Hub GitLab spoke. Install the spoke and navigate to Process Automation > Flow Designer to access GitLab actions including 'Get Merge Request', 'Update Merge Request', 'Get Pipeline', and 'Create Issue'. Configure the spoke by setting up a Connection Alias step in your flows pointing to the GitLab_Connection created earlier. Verify the spoke installation by checking that GitLab actions appear in the Action browser under the IntegrationHub category.

4

Create Scripted REST API for GitLab Webhook Events

Navigate to System Web Services > Scripted REST APIs and create a new API named 'GitLabWebhookHandler' with the API ID 'gitlab_webhook'. Create a POST resource named 'events' that will handle incoming webhook payloads from GitLab. Configure the resource to accept JSON content type and implement authentication using a shared secret or API key validation. The script should parse different GitLab event types including push events, merge request events, and pipeline events, then route them to appropriate ServiceNow record creation or update logic.

ServiceNow Script
(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {
    var payload = request.body.data;
    var eventType = request.getHeader('X-Gitlab-Event');
    
    if (eventType == 'Push Hook') {
        handlePushEvent(payload);
    } else if (eventType == 'Merge Request Hook') {
        handleMergeRequestEvent(payload);
    } else if (eventType == 'Pipeline Hook') {
        handlePipelineEvent(payload);
    }
    
    response.setStatus(200);
    response.setBody({status: 'received'});
    
    function handlePushEvent(data) {
        var gr = new GlideRecord('change_request');
        if (gr.get('u_gitlab_commit_ref', data.ref)) {
            gr.state = 3; // Implement
            gr.update();
        }
    }
})(request, response);
5

Configure GitLab Webhooks to Send Events to ServiceNow

In your GitLab project or group, navigate to Settings > Webhooks and create a new webhook pointing to your ServiceNow Scripted REST API endpoint (https://your-instance.service-now.com/api/now/gitlab_webhook/events). Select the events you want to monitor including Push events, Merge request events, Pipeline events, and Issues events based on your integration requirements. Configure the webhook secret token to match the authentication mechanism implemented in your Scripted REST API for security. Test the webhook using GitLab's test feature to ensure ServiceNow receives and processes the payload correctly.

6

Create Integration Hub Flow for Change Request Automation

Navigate to Process Automation > Flow Designer and create a new flow triggered by Change Request record creation or update. Add a condition to check if the change is related to a code deployment by examining fields like deployment method or change category. Include GitLab actions to retrieve merge request details, check pipeline status, and update the change request with deployment information. Configure error handling to manage API failures and implement retry logic for transient network issues.

7

Implement Merge Request to Change Record Linking

Create a Business Rule or Flow that executes when merge requests are created or updated to automatically link them to existing change requests. Use the GitLab 'Get Merge Request' action to retrieve merge request details including branch names, commit messages, and author information. Parse commit messages for change request numbers using regular expressions and create relationships between GitLab merge requests and ServiceNow change records using a custom many-to-many table or reference fields. Implement validation to ensure only valid change request numbers are linked and handle cases where multiple change requests are referenced in a single merge request.

ServiceNow Script
var rm = new sn_ws.RESTMessageV2('GitLab', 'GET');
rm.setStringParameterNoEscape('project_id', current.u_gitlab_project_id);
rm.setStringParameterNoEscape('merge_request_iid', current.u_gitlab_mr_iid);
rm.setRequestHeader('PRIVATE-TOKEN', gs.getProperty('gitlab.api.token'));

var response = rm.execute();
if (response.getStatusCode() == 200) {
    var mrData = JSON.parse(response.getBody());
    var commitMsg = mrData.description;
    var changePattern = /CHG\d{7}/g;
    var matches = commitMsg.match(changePattern);
    
    if (matches) {
        for (var i = 0; i < matches.length; i++) {
            var chg = new GlideRecord('change_request');
            if (chg.get('number', matches[i])) {
                chg.u_gitlab_mr_url = mrData.web_url;
                chg.update();
            }
        }
    }
}
8

Test and Validate the Complete Integration

Create a test change request in ServiceNow with appropriate GitLab project references and trigger a corresponding merge request in GitLab to verify the bi-directional data flow works correctly. Test webhook delivery by performing various GitLab actions like creating merge requests, pushing commits, and running pipelines while monitoring ServiceNow system logs for successful webhook processing. Validate that GitLab API calls from ServiceNow are working by checking the REST Message logs under System Logs > REST Messages and confirming that authentication tokens are being accepted. Perform end-to-end testing by creating a change request, associating it with a GitLab merge request, and verifying that pipeline status updates are reflected in ServiceNow change records.

Common Use Cases

Automated Change Request Creation from Merge Requests

When developers create merge requests in GitLab targeting production branches, ServiceNow automatically generates corresponding change requests with pre-populated fields including deployment window, technical details, and risk assessment. The integration extracts information from merge request descriptions, commit messages, and associated Jira tickets to populate change request fields like business justification and implementation plan. This ensures all production deployments follow organizational change management processes while reducing manual overhead for development teams and maintaining compliance audit trails.

Pipeline Status Integration with Change Management

GitLab CI/CD pipeline events automatically update ServiceNow change request states based on deployment success or failure, with successful deployments moving changes to 'Implemented' status and failures triggering 'Failed' status with incident creation. The integration captures pipeline logs, test results, and deployment metrics to provide change managers visibility into technical implementation details without requiring GitLab access. Failed deployments automatically create incidents in ServiceNow with relevant technical context, assigned to appropriate technical teams based on project ownership and on-call schedules.

Incident Creation from GitLab Alerts and Monitoring

GitLab's built-in monitoring, security scanning, and dependency vulnerability alerts trigger automatic incident creation in ServiceNow with appropriate priority and assignment based on alert severity and affected systems. Security vulnerabilities detected in GitLab projects create security incidents with CVSS scores, affected components, and recommended remediation steps automatically populated in ServiceNow incident records. Performance alerts and deployment failures from GitLab environments create operational incidents with relevant logs, metrics, and context to enable rapid response from ServiceNow-based support teams.

Release Management and Deployment Tracking

ServiceNow release records automatically aggregate related change requests that reference GitLab merge requests, providing comprehensive visibility into all code changes included in a release cycle. The integration tracks deployment status across multiple environments by monitoring GitLab deployment events and updating ServiceNow release records with environment-specific deployment timestamps and success metrics. Release managers can view consolidated deployment status, rollback procedures, and impact assessment across all applications and environments from ServiceNow without accessing individual GitLab projects.

Compliance Reporting and Audit Trail Maintenance

The integration maintains complete audit trails by linking every production code change to approved ServiceNow change requests, capturing approver information, deployment timestamps, and post-deployment validation results. Compliance reports automatically generate from ServiceNow showing the relationship between business requirements, approved changes, and actual code deployments with full traceability through GitLab commit history. Unauthorized deployments are detected when GitLab deployment events occur without corresponding approved change requests, triggering alerts to compliance teams and potentially automated rollback procedures.

Troubleshooting

GitLab webhook returns 401 Unauthorized when calling ServiceNow REST API

Check that the webhook URL includes proper authentication or that your Scripted REST API resource has the correct security settings configured. Navigate to System Logs > REST API to examine the authentication failure details and verify that the webhook secret token matches your API validation logic. Ensure the ServiceNow user associated with the API call has sufficient roles including rest_service and any custom roles required for the target table operations.

Integration Hub GitLab actions fail with SSL certificate errors

For self-hosted GitLab instances with self-signed certificates, navigate to your Connection & Credential Alias and temporarily enable 'Ignore SSL Certificate Errors' for testing, but implement proper certificate validation for production environments. Check that your GitLab instance's SSL certificate chain is complete and trusted, and consider importing the certificate authority into ServiceNow's certificate store. If using a MID Server, ensure it trusts the GitLab instance's certificates and can establish secure connections.

Merge request details not updating in ServiceNow change records

Verify that your Integration Hub flow or Business Rule is properly triggered by examining the Flow execution history under Process Automation > Flow Designer > Executions. Check the GitLab API rate limits and response codes in System Logs > REST Messages to identify if requests are being throttled or failing due to insufficient permissions. Confirm that the GitLab personal access token has the necessary scopes (api, read_api, read_repository) and hasn't expired, and test the Connection & Credential Alias connectivity.

Webhook payload received but no ServiceNow records created or updated

Enable debug logging for your Scripted REST API by adding gs.log statements and check System Logs > System Log for execution details and any JavaScript errors. Verify the webhook payload structure matches your parsing logic by logging the request.body.data content and comparing it to GitLab's webhook documentation for your specific event types. Check that the event type header parsing logic correctly identifies GitLab events and routes them to appropriate handler functions.

Change requests showing incorrect GitLab pipeline status

Examine the timing of webhook deliveries versus ServiceNow processing by checking webhook delivery logs in GitLab and corresponding REST API execution logs in ServiceNow to identify delays or failed deliveries. Verify that your pipeline status mapping logic correctly translates GitLab pipeline states (pending, running, success, failed, canceled) to appropriate ServiceNow change request states. Consider implementing retry mechanisms for webhook processing failures and ensure your webhook endpoint returns appropriate HTTP status codes to GitLab.

Integration fails with 'Connection timed out' errors

Check network connectivity between ServiceNow and GitLab by testing the Connection & Credential Alias and examining any firewall or proxy configurations that might block HTTPS traffic on port 443. If using a MID Server, verify it's running and accessible to both ServiceNow and your GitLab instance, and check MID Server logs for connection issues. Increase REST message timeout values in your Integration Hub actions or REST Message records if GitLab API responses are consistently slow, and consider implementing asynchronous processing for large data transfers.

Pro Tips

  • Implement webhook secret validation in your Scripted REST APIs using HMAC-SHA256 signature verification to prevent unauthorized webhook calls and potential security breaches. Store the webhook secret in ServiceNow system properties and validate the X-GitLab-Token header against the computed signature of the request body.
  • Use ServiceNow's REST Message retry capabilities by configuring exponential backoff for GitLab API calls to handle transient network issues and API rate limits gracefully. Set up Flow Designer error handling with retry logic and implement dead letter queues for failed webhook processing.
  • Create custom ServiceNow tables to store GitLab project mappings, webhook configurations, and API rate limit tracking to provide administrators with visibility into integration health and performance metrics. This enables proactive monitoring and troubleshooting of integration issues.
  • Leverage ServiceNow's Transform Maps for webhook payload processing to provide a declarative approach to mapping GitLab event data to ServiceNow record fields, making the integration more maintainable and reducing custom scripting requirements.
  • Implement ServiceNow Event-driven architecture by generating custom ServiceNow events from GitLab webhooks and using Event Rules to trigger appropriate workflows, enabling loose coupling and better scalability for complex integration scenarios.
  • Use ServiceNow's Data Source feature to periodically sync GitLab project metadata, user information, and repository statistics for reporting and analytics purposes, complementing the real-time webhook-based integration with comprehensive data synchronization.

Known Limitations

  • GitLab's webhook delivery is best-effort and may fail during network issues or ServiceNow maintenance windows, requiring implementation of webhook retry mechanisms or periodic reconciliation jobs to ensure data consistency. GitLab webhooks have a 10-second timeout limit, so ServiceNow processing must complete quickly or use asynchronous processing patterns to avoid webhook failures.
  • The Integration Hub GitLab spoke supports only the most common GitLab API operations and may require custom REST Message implementations for advanced features like GitLab GraphQL API access, detailed merge request analytics, or GitLab Container Registry integration. Complex GitLab workflow automation may exceed Integration Hub licensing limits for high-volume environments.
  • ServiceNow's REST API rate limits (100 requests per minute for basic users, 1000 for admin users) may be insufficient for large GitLab environments with frequent webhook events, requiring careful rate limit management and potentially upgrading ServiceNow licensing tiers. GitLab API rate limits of 2000 requests per minute may impact real-time synchronization in enterprise environments with multiple projects.
  • Webhook-based integration creates eventual consistency scenarios where ServiceNow data may be temporarily out of sync with GitLab state during network partitions or processing failures, requiring careful consideration of business processes that depend on real-time data accuracy. Large webhook payloads may exceed ServiceNow's maximum request size limits, particularly for merge requests with extensive diff information.

Frequently Asked Questions

Can this integration work with GitLab.com SaaS and on-premises ServiceNow instances?

Yes, the integration works between GitLab.com and ServiceNow instances in any deployment model, as long as ServiceNow can reach GitLab's APIs over HTTPS and GitLab can deliver webhooks to ServiceNow endpoints. For ServiceNow instances behind firewalls, configure webhook URLs to use publicly accessible endpoints or implement webhook relay mechanisms. Network connectivity requirements are outbound HTTPS from ServiceNow to GitLab and inbound HTTPS from GitLab to ServiceNow for webhook delivery.

How can I handle GitLab webhook failures and ensure no events are lost?

GitLab automatically retries failed webhooks up to 3 times with exponential backoff, but you should implement additional resilience by enabling GitLab's webhook logs to monitor delivery failures and creating ServiceNow scheduled jobs to periodically reconcile data using GitLab's REST API. Consider implementing idempotent webhook processing in ServiceNow to handle duplicate deliveries safely, and use ServiceNow's Event Management to track integration health. For critical integrations, implement a dead letter queue pattern using ServiceNow tables to capture and replay failed webhook events.

What permissions are required for the GitLab personal access token used in this integration?

The GitLab personal access token requires 'api' scope for full API access including merge request creation and updates, 'read_api' for reading project information and user details, 'read_repository' for accessing commit information and branch details, and optionally 'write_repository' if the integration needs to create branches or tags from ServiceNow. For security scanning and compliance features, add 'read_registry' scope to access container image vulnerability data. The token should belong to a GitLab user with at least Developer role in the projects being integrated, or use a service account with appropriate project-level permissions.

Can I integrate multiple GitLab projects or instances with a single ServiceNow instance?

Yes, you can integrate multiple GitLab projects and instances by creating separate Connection & Credential Aliases for each GitLab instance and configuring project-specific mappings in your Integration Hub flows or Scripted REST APIs. Use ServiceNow custom tables to store GitLab project configurations, webhook URLs, and instance mappings to support multi-tenant scenarios. Implement namespace isolation in your webhook processing logic to route events from different GitLab projects to appropriate ServiceNow applications or business units. Consider using ServiceNow's domain separation if different GitLab instances serve different organizational units.

How does this integration handle GitLab merge request approvals and ServiceNow change approvals?

The integration can synchronize approval states bidirectionally by using GitLab's merge request approval API to check approval status and update ServiceNow change request approval states accordingly. Implement ServiceNow approval workflow automation that creates or updates GitLab merge request approvals when ServiceNow change requests receive required approvals, ensuring both systems maintain consistent approval states. Use GitLab webhook events for merge request approval changes to trigger ServiceNow approval workflow updates, and consider implementing approval delegation between GitLab and ServiceNow based on organizational approval matrices. Configure the integration to enforce approval dependencies, such as requiring ServiceNow change approval before allowing GitLab merge request completion.

What monitoring and alerting capabilities are available for this integration?

ServiceNow provides comprehensive monitoring through Integration Hub execution history, REST Message logs, and Event Management capabilities that can track webhook delivery success rates, API response times, and integration failure patterns. Create ServiceNow Performance Analytics dashboards to visualize integration metrics like change request automation rates, deployment success rates, and webhook processing times. Implement custom ServiceNow alerts using Event Rules to notify administrators of integration failures, API rate limit violations, or authentication issues, and use ServiceNow's Health Log Viewer to monitor system performance impact. GitLab's webhook settings page provides delivery history and failure logs that complement ServiceNow's monitoring capabilities.

Can this integration support GitLab Security scanning results in ServiceNow Security Incident Response?

Yes, GitLab security scanning results can be integrated with ServiceNow Security Incident Response (SIR) by configuring webhooks for GitLab security events and creating SIR incidents automatically based on vulnerability severity and type. Use GitLab's Vulnerability Report API to retrieve detailed security findings including CVSS scores, affected files, and remediation recommendations, then populate SIR incident records with this technical context. Implement automated assignment of security incidents based on GitLab project ownership and vulnerability type, and create ServiceNow workflows that track remediation progress back to GitLab merge requests and security dashboard updates. The integration can also sync remediation status from ServiceNow back to GitLab to update vulnerability states and close security findings.

Test Your Knowledge

Quick 3-question quiz — see how your ServiceNow skills stack up.

Question 1 of 3Performance

A list view on a table with millions of records is slow. Best fix?

Select an answer to continue