The ServiceNow Ansible integration enables organizations to automate infrastructure provisioning, configuration management, and incident remediation by connecting ServiceNow's workflow engine with Ansible Automation Platform's job execution capabilities. This integration is primarily used by IT operations teams, infrastructure engineers, and service delivery managers who need to orchestrate complex automation workflows triggered by ServiceNow change requests, incidents, or scheduled maintenance activities. The integration supports bi-directional data flows including launching Ansible job templates from ServiceNow change management workflows, synchronizing CMDB inventory data with Ansible inventories, and automatically creating ServiceNow incidents based on Ansible playbook execution results. The primary automation patterns involve triggering Ansible job templates through ServiceNow business rules or Flow Designer, with the integration residing primarily in the IT Service Management and IT Operations Management modules through the official Red Hat Ansible Automation Platform spoke.
Prerequisites
- •ServiceNow Utah release or later with Integration Hub Professional license
- •Red Hat Ansible Automation Platform 2.0 or later with API access enabled
- •ServiceNow MID Server with outbound internet connectivity to Ansible Automation Platform
- •Red Hat Ansible Automation Platform spoke installed from ServiceNow Store
- •System Administrator or integration_user role in ServiceNow
- •Organization Administrator or Automation Execution role in Ansible Automation Platform
- •Valid SSL certificates configured on Ansible Automation Platform controller
Architecture Overview
The integration utilizes the official Red Hat Ansible Automation Platform spoke from the ServiceNow Store, which provides pre-built Flow Designer actions for job template execution, inventory synchronization, and credential management. Authentication is established using OAuth 2.0 tokens stored in ServiceNow Connection & Credential Aliases, with credentials securely managed through the Credential Store under System Security. Data flows bi-directionally with ServiceNow initiating outbound REST API calls to launch Ansible job templates and receive execution status, while Ansible can send webhook notifications back to ServiceNow for job completion updates. A MID Server is required for this integration to handle outbound HTTPS connections to Ansible Automation Platform, especially in environments where ServiceNow instances are behind corporate firewalls or need to communicate with on-premises Ansible installations. The Ansible Automation Platform API has rate limiting of 1000 requests per hour per user by default, and the spoke implements proper retry logic and job polling mechanisms to handle API quotas gracefully.
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
Install Red Hat Ansible Automation Platform spoke from ServiceNow Store
Navigate to System Applications > All Available Applications > All and search for 'Red Hat Ansible Automation Platform'. Click on the official Red Hat spoke and select Install. The installation process will create the necessary tables, Flow Designer actions, and configuration records required for the integration. After installation completes, verify that the spoke is active by checking System Applications > My Company Applications and confirming the 'Red Hat Ansible Automation Platform' entry shows as Active. The spoke installation typically takes 5-10 minutes and includes actions for launching job templates, managing inventories, and retrieving job execution results.
Create OAuth application token in Ansible Automation Platform
Log into your Ansible Automation Platform web interface and navigate to Administration > Applications. Click the Add button to create a new application with Application Type set to 'Personal Access Token' or 'Application'. Record the Client ID and Client Secret values as these will be needed for ServiceNow credential configuration. Set the Authorization Grant Type to 'Authorization Code' and configure the redirect URI to match your ServiceNow instance URL format. Ensure the application has appropriate permissions including 'Read' and 'Write' access to job templates, inventories, and projects that will be managed through ServiceNow integration.
Configure Connection Alias and Credential in ServiceNow
Navigate to Connections & Credentials > Connection & Credential Aliases and click New to create a connection alias for Ansible Automation Platform. Set the Name field to 'Ansible_AAP_Connection' and Type to 'HTTP(S)'. In the Connection URL field, enter your Ansible Automation Platform controller URL (e.g., https://ansible-controller.company.com). Create a new Credential by clicking the lock icon next to Credential field, select 'OAuth 2.0' as credential type, and enter the Client ID and Client Secret from step 2. Set the OAuth Entity Profile to point to your Ansible Automation Platform OAuth endpoints for token generation and validation.
// Test the connection with this script in Scripts - Background
var request = new RESTMessage('Ansible_AAP_Connection', 'get');
request.setEndpoint('https://ansible-controller.company.com/api/v2/me/');
request.setRequestHeader('Content-Type', 'application/json');
var response = request.execute();
gs.info('Response Status: ' + response.getStatusCode());
gs.info('Response Body: ' + response.getBody());Configure MID Server for Ansible Automation Platform connectivity
Navigate to MID Server > Servers and select your target MID Server that will handle Ansible integration traffic. Validate that the MID Server can reach your Ansible Automation Platform controller by testing connectivity on the required ports (typically 443 for HTTPS). If using an on-premises Ansible installation, ensure the MID Server has network connectivity to the Ansible controller and any required firewall rules are configured. Update the MID Server parameters to include any necessary proxy configurations or certificate trust settings for your Ansible environment. Test the connectivity by running a basic REST message through the MID Server to the Ansible API endpoint.
// MID Server connectivity test script
var midServer = 'YOUR_MID_SERVER_NAME';
var request = new RESTMessage();
request.setEndpoint('https://ansible-controller.company.com/api/v2/ping/');
request.setHttpMethod('GET');
request.setMIDServer(midServer);
var response = request.execute();
gs.info('MID Server: ' + midServer + ', Status: ' + response.getStatusCode());Create Flow Designer subflow for launching Ansible job templates
Navigate to Process Automation > Flow Designer and create a new subflow named 'Launch Ansible Job Template'. Add the 'Ansible Automation Platform - Launch Job Template' action from the installed spoke, and configure it with your connection alias from step 3. Configure input variables for job_template_id, extra_vars (as JSON string), and limit parameters to make the subflow reusable across different automation scenarios. Add error handling logic using the Flow Designer Try/Catch actions to manage API failures, timeouts, or job execution errors. Include a polling mechanism using the 'Ansible Automation Platform - Get Job' action to monitor job status and wait for completion before proceeding with downstream workflow steps.
// Sample script to prepare extra_vars JSON for Ansible job template
var extraVars = {
'target_host': current.cmdb_ci.ip_address.toString(),
'service_account': 'svc_automation',
'change_request': current.number.toString(),
'environment': current.environment.toString()
};
var extraVarsJson = JSON.stringify(extraVars);
gs.info('Extra vars for Ansible: ' + extraVarsJson);Configure Change Management workflow integration
Navigate to Change > Change Requests and access the Change Request form configuration. Create a new Flow Designer flow triggered on Change Request state changes to 'Implement' that calls your Ansible job template subflow from step 5. Configure the flow to extract relevant change request details like target CMDB CI, change type, and implementation window to pass as variables to the Ansible playbook. Add conditional logic to only trigger automation for specific change categories or risk levels to prevent unintended automation execution. Include proper logging and status updates back to the change request record using the 'Update Record' action to track automation progress and results.
// Business rule to prepare change data for Ansible automation
(function executeRule(current, previous) {
if (current.state == '3' && previous.state != '3') { // Implement state
var changeData = {
change_number: current.number.toString(),
ci_name: current.cmdb_ci.name.toString(),
implementation_plan: current.implementation_plan.toString(),
requested_by: current.requested_by.getDisplayValue()
};
// Trigger Flow Designer flow with change data
gs.eventQueue('ansible.change.implement', current, JSON.stringify(changeData));
}
})(current, previous);Set up CMDB inventory synchronization
Create a scheduled Flow Designer flow that runs daily to synchronize ServiceNow CMDB data with Ansible inventories using the 'Ansible Automation Platform - Update Inventory' spoke action. Configure the flow to query CMDB CI records using GlideRecord operations and format the data according to Ansible inventory JSON structure with proper host groups and variables. Map ServiceNow CI attributes like IP addresses, operating systems, and business services to corresponding Ansible inventory variables for use in playbooks. Include delta synchronization logic to only update inventory items that have changed since the last sync operation, reducing API calls and improving performance. Add error handling for inventory update failures and logging mechanisms to track synchronization status and conflicts.
// Script to build Ansible inventory from CMDB data
var inventory = {
'_meta': {
'hostvars': {}
}
};
var servers = new GlideRecord('cmdb_ci_server');
servers.addQuery('operational_status', '1'); // Operational
servers.query();
while (servers.next()) {
var hostName = servers.name.toString();
inventory._meta.hostvars[hostName] = {
'ansible_host': servers.ip_address.toString(),
'os_family': servers.os.toString(),
'environment': servers.environment.toString(),
'business_service': servers.business_service.getDisplayValue()
};
var osGroup = servers.os.toString().replace(/\s+/g, '_').toLowerCase();
if (!inventory[osGroup]) inventory[osGroup] = {'hosts': []};
inventory[osGroup].hosts.push(hostName);
}
gs.info('Generated inventory: ' + JSON.stringify(inventory, null, 2));Configure incident remediation automation
Navigate to Incident > Create New and configure a Flow Designer flow triggered on high-priority incident creation that automatically launches remediation Ansible playbooks based on incident category and CMDB CI type. Use the incident's Assignment Group and Category fields to determine which Ansible job templates to execute for automated remediation attempts. Configure the flow to update the incident work notes with Ansible job execution details, including job ID, status, and any error messages returned from the automation platform. Add logic to automatically resolve incidents when Ansible remediation jobs complete successfully, or escalate to human intervention when automation fails. Include proper timeout handling to prevent indefinite waiting for job completion and ensure incidents are not left in pending automation states.
// Incident automation trigger script
(function executeRule(current, previous) {
if (current.priority <= '2' && current.state == '2') { // High priority, In Progress
var remediationMap = {
'hardware': 'hardware_diagnostics_playbook',
'software': 'software_restart_playbook',
'network': 'network_connectivity_playbook'
};
var category = current.category.toString();
var playbookTemplate = remediationMap[category];
if (playbookTemplate) {
var automationData = {
incident_number: current.number.toString(),
target_ci: current.cmdb_ci.sys_id.toString(),
priority: current.priority.toString(),
playbook_template: playbookTemplate
};
gs.eventQueue('ansible.incident.remediate', current, JSON.stringify(automationData));
}
}
})(current, previous);Common Use Cases
Automated server patching through change management
Change requests for server patching automatically trigger Ansible playbooks that perform pre-patch backups, apply operating system updates, and conduct post-patch validation testing. The change request workflow integrates with Ansible job templates that handle different server types (Linux, Windows) and environments (development, staging, production) with appropriate approval gates and rollback procedures. ServiceNow tracks patch compliance status by receiving job execution results and updating CMDB CI records with current patch levels and compliance scores. This use case delivers business value by reducing manual patching effort by 70% while maintaining audit trails and compliance reporting through ServiceNow's change management processes.
Infrastructure provisioning for service requests
Service catalog requests for new virtual machines or applications automatically launch Ansible playbooks that provision infrastructure resources, configure networking, and deploy application stacks based on standardized templates. The integration passes service request parameters like environment type, resource specifications, and business owner information as extra variables to Ansible playbooks for dynamic resource creation. CMDB discovery automatically populates new CI records for provisioned resources, establishing configuration relationships and dependency mappings for ongoing service management. This automation reduces average provisioning time from days to hours while ensuring consistent configuration standards and eliminating manual provisioning errors.
Incident remediation automation
High-priority incidents automatically trigger diagnostic and remediation Ansible playbooks based on incident category, affected CI type, and historical resolution patterns stored in ServiceNow knowledge base. The integration launches multi-step automation workflows that perform service health checks, restart failed services, clear disk space, or reset network connections depending on incident symptoms and CMDB CI relationships. Successful automated remediations automatically resolve incidents with detailed work notes, while failed automation attempts escalate to human operators with diagnostic data and recommended manual intervention steps. Organizations typically see 40-60% of Level 1 incidents automatically resolved without human intervention, significantly reducing MTTR and improving service availability.
Compliance and security automation
Scheduled compliance scans trigger Ansible playbooks that audit server configurations, validate security policies, and remediate configuration drift based on organizational security baselines and industry frameworks like CIS benchmarks. The integration creates ServiceNow security incidents for compliance violations, tracks remediation progress through change requests, and updates risk assessment scores in the Governance, Risk, and Compliance (GRC) application. Ansible playbooks automatically apply security patches, update firewall rules, and reconfigure system settings to maintain compliance posture across hybrid infrastructure environments. This use case provides continuous compliance monitoring and automated remediation, reducing compliance audit preparation time and ensuring consistent security policy enforcement.
Application deployment and rollback automation
Release management processes automatically coordinate application deployments across multiple environments using Ansible playbooks that handle code deployment, database migrations, configuration updates, and service validation testing. The integration manages deployment pipelines with proper approval workflows, automated testing gates, and rollback procedures triggered through ServiceNow change management processes. Real-time deployment status updates flow back to ServiceNow, updating release records with deployment progress, test results, and any errors encountered during the automation process. Failed deployments automatically trigger rollback playbooks and create problem records for root cause analysis, ensuring rapid recovery and maintaining detailed audit trails for regulatory compliance and post-deployment reviews.
Troubleshooting
401 Unauthorized error when launching Ansible job templates from ServiceNow
First, verify that the OAuth token in your Connection & Credential Alias is still valid by testing the connection manually in the Credentials module. Check the Ansible Automation Platform application settings to ensure the ServiceNow integration application has not been disabled or had its permissions modified. Review the System Log > Outbound HTTP Requests to examine the actual authentication headers being sent and compare them with Ansible's expected OAuth format. If using token-based authentication, regenerate the token in Ansible Automation Platform and update the ServiceNow credential record, ensuring the new token has appropriate job template execution permissions.
Ansible job templates launch successfully but ServiceNow never receives completion status
Check the MID Server logs to verify that the polling mechanism for job status is functioning correctly and not timing out due to network connectivity issues. Navigate to System Log > System Log > All to look for integration-related errors during the job status polling process. Verify that the Ansible Automation Platform API endpoints for job status queries are accessible from your MID Server and not blocked by firewall rules. Increase the polling timeout values in your Flow Designer subflow or implement webhook-based status updates from Ansible to ServiceNow for more reliable job completion notifications.
CMDB inventory synchronization fails with timeout errors
Review the size of your CMDB dataset being synchronized and implement pagination in your inventory sync Flow Designer flow to process CIs in smaller batches of 100-500 records. Check the Ansible Automation Platform inventory API rate limits and add appropriate delays between API calls using Flow Designer Wait actions. Examine the System Log > Integration Logs for specific timeout error messages and adjust the REST message timeout values in your connection configuration. Consider implementing incremental sync logic that only processes CMDB CIs modified since the last successful synchronization to reduce API load and processing time.
Flow Designer actions fail with 'Connection not found' error message
Verify that your Connection & Credential Alias name exactly matches the connection reference used in your Flow Designer actions, as these references are case-sensitive and must match precisely. Check that the MID Server specified in your connection configuration is online and properly associated with your ServiceNow instance by reviewing MID Server > Servers status page. Navigate to Connections & Credentials > Connection & Credential Aliases and test the connection manually using the Test Connection button to verify connectivity and authentication. If the connection test passes but Flow Designer actions still fail, clear the Flow Designer cache and republish your flows to ensure they use the updated connection configuration.
Ansible playbook execution fails with variable parsing errors
Review the extra_vars JSON structure being passed from ServiceNow to ensure it contains valid JSON syntax and all required variables expected by the Ansible playbook. Use the Script Background module to test JSON.stringify() operations on your variable data and verify the output matches Ansible's expected format. Check the Ansible job template configuration in Automation Platform to ensure variable names match exactly between ServiceNow and Ansible, including case sensitivity and data type requirements. Add JSON validation logic to your Flow Designer flows before launching job templates to catch variable formatting errors and provide meaningful error messages back to ServiceNow users.
High-priority incidents trigger multiple concurrent Ansible jobs causing resource conflicts
Implement job queuing logic in your incident remediation flows using ServiceNow's Flow Designer Wait for Condition actions to check for existing running jobs before launching new automation. Create a custom table to track active Ansible automation jobs by target CI and incident number, preventing duplicate job launches for the same infrastructure component. Configure Ansible job template settings to use job limiting and queuing features that prevent concurrent execution of conflicting automation tasks. Add business rule logic to incident forms that checks for existing automation activities and either queues new jobs or consolidates multiple incidents targeting the same CI into a single remediation workflow.
Pro Tips
- →Implement custom job status polling intervals based on expected Ansible playbook execution time rather than using fixed polling intervals, reducing unnecessary API calls and improving integration performance. Create different polling strategies for quick diagnostic playbooks (30-second intervals) versus long-running deployment playbooks (5-minute intervals) to optimize resource usage and user experience.
- →Use ServiceNow's Event Management to create custom events for Ansible job state changes and configure event rules that automatically update related change requests, incidents, or service requests based on automation outcomes. This pattern provides better integration resilience and allows for complex workflow orchestration beyond simple success/failure scenarios.
- →Store frequently used Ansible extra_vars templates as ServiceNow System Properties or in custom configuration tables to maintain consistency across different automation workflows and reduce configuration drift. This approach also enables non-technical users to modify automation parameters without editing Flow Designer flows or business rules.
- →Implement Ansible inventory caching in ServiceNow using custom tables that mirror your CMDB structure but optimized for Ansible consumption, reducing real-time CMDB queries during job template launches. Update these cache tables using scheduled jobs and trigger immediate updates when critical CMDB changes occur through business rules.
- →Create ServiceNow dashboards and performance analytics to track Ansible automation success rates, execution times, and resource utilization patterns across different job templates and infrastructure components. Use this data to optimize playbook performance and identify automation opportunities for manual processes.
- →Configure separate Connection & Credential Aliases for different Ansible Automation Platform environments (development, staging, production) and use ServiceNow's environment-based routing to ensure change management workflows automatically select appropriate automation targets based on the CMDB CI's environment classification.
Known Limitations
- —Ansible Automation Platform API rate limiting restricts organizations to 1000 API calls per hour per authenticated user by default, which can impact high-volume automation scenarios or frequent CMDB inventory synchronization operations. Large enterprises may need to implement request queuing, multiple API users, or upgrade to higher API tier limits to support their automation volume requirements.
- —The integration requires continuous network connectivity between ServiceNow MID Servers and Ansible Automation Platform controllers, making it unsuitable for air-gapped environments or scenarios requiring offline automation execution. Network latency and firewall configurations can significantly impact job launch times and status polling reliability, especially for geographically distributed infrastructure.
- —ServiceNow Flow Designer has execution time limits of 10 minutes per flow action, which may cause timeouts for long-running Ansible playbooks that exceed this threshold. Complex automation workflows requiring sequential execution of multiple Ansible job templates may need custom asynchronous handling or workflow splitting to avoid ServiceNow platform execution limits.
- —CMDB inventory synchronization is limited by ServiceNow's table query performance and Ansible's inventory size constraints, typically supporting up to 10,000 hosts per inventory group efficiently. Organizations with larger infrastructure footprints may need to implement inventory sharding, selective synchronization, or custom caching mechanisms to maintain acceptable performance levels.
- —The Red Hat Ansible Automation Platform spoke requires Integration Hub Professional licensing, which adds significant cost considerations for ServiceNow implementations and may not be available in all ServiceNow subscription tiers. Additionally, the spoke's update cycle is independent of ServiceNow releases, potentially creating compatibility issues during ServiceNow platform upgrades.
Frequently Asked Questions
Can I use this integration with Ansible Tower or do I need Ansible Automation Platform?
The Red Hat Ansible Automation Platform spoke supports both Ansible Tower (versions 3.x) and the newer Ansible Automation Platform (versions 2.x and later) since they share compatible REST API endpoints. However, Red Hat recommends migrating to Ansible Automation Platform for continued support and access to new features. The spoke automatically detects API version differences and adjusts its requests accordingly, ensuring compatibility across different Ansible controller versions.
How do I handle Ansible playbooks that require interactive input or approval during execution?
Ansible playbooks requiring interactive input are not compatible with ServiceNow automation workflows since the integration cannot handle mid-execution user prompts or approvals. Design your Ansible playbooks to accept all required parameters through extra_vars or job template survey specifications configured in Ansible Automation Platform. For scenarios requiring human approval, implement the approval logic in ServiceNow's workflow (using Flow Designer approval actions) before launching the Ansible job template, ensuring all necessary decisions are made within ServiceNow's approval framework.
What happens if my ServiceNow instance is upgraded while Ansible jobs are running?
ServiceNow instance upgrades typically do not interrupt actively running Ansible jobs since the job execution occurs on the Ansible Automation Platform infrastructure. However, job status polling and completion notification flows may be disrupted during the upgrade window, potentially leaving ServiceNow records in pending states. After upgrade completion, implement cleanup scripts to reconcile any orphaned job references and manually verify completion status for jobs that were running during the upgrade window. The Red Hat spoke includes upgrade-safe design patterns that minimize integration disruption during ServiceNow maintenance windows.
Can I trigger different Ansible playbooks based on ServiceNow user roles or groups?
Yes, you can implement role-based automation by using ServiceNow's user role checking functions (gs.hasRole()) within Flow Designer conditional actions or business rules before launching Ansible job templates. Create different job template mappings based on user roles, allowing help desk operators access to basic diagnostic playbooks while restricting infrastructure engineers to advanced configuration and deployment automation. This approach maintains security boundaries while enabling self-service automation capabilities. Additionally, you can pass user role information as extra_vars to Ansible playbooks for audit logging and privilege escalation decisions within the automation workflow.
How do I monitor and alert on Ansible automation failures within ServiceNow?
Configure Event Management rules to create alerts when Ansible job templates fail by monitoring job status responses and creating events for non-successful completion states. Use ServiceNow's Notification framework to send email or Slack messages to operations teams when critical automation workflows fail, including job logs and error details in the notification content. Implement custom dashboards using Performance Analytics to visualize automation success rates, failure trends, and mean time to resolution for automation-related incidents. Create problem records automatically for recurring Ansible job failures to trigger root cause analysis and prevent future automation issues.
Can I use this integration to manage Ansible Galaxy collections and execution environments?
The Red Hat Ansible Automation Platform spoke focuses primarily on job template execution and inventory management rather than Ansible Galaxy collection or execution environment lifecycle management. However, you can create ServiceNow change management workflows that trigger Ansible playbooks designed to update collections, sync Galaxy content, or deploy new execution environments to your Ansible infrastructure. This approach treats collection and environment updates as infrastructure changes managed through ServiceNow's change control processes while leveraging Ansible's own automation capabilities for the actual deployment tasks.
What authentication methods work best for enterprise environments with strict security requirements?
For enterprise environments, implement OAuth 2.0 with short-lived tokens and automated token refresh mechanisms rather than long-lived API keys or basic authentication methods. Configure separate service accounts in Ansible Automation Platform for different ServiceNow integration use cases (change management, incident response, inventory sync) to enable granular access control and audit logging. Use ServiceNow's Credential Store encryption and consider implementing certificate-based authentication for additional security layers. Regularly rotate authentication credentials and monitor API access logs in both ServiceNow and Ansible Automation Platform for unauthorized access attempts or unusual usage patterns.
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