AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible ServiceNow Integration: Automate ITSM Workflows and Change Management

By Luca Berton · Published 2024-01-01 · Category: installation

Integrate Ansible with ServiceNow for automated change management, incident response, and CMDB updates. ITSM automation with AAP and servicenow.itsm collection.

Introduction

ServiceNow is the enterprise standard for IT Service Management (ITSM) — handling incidents, changes, problems, and asset tracking. But manual ticket creation, approval workflows, and CMDB updates slow down automation. By integrating Ansible with ServiceNow, you can automate the ITSM process alongside infrastructure changes — creating change requests, getting approvals, executing automation, and closing tickets in a single workflow.

See also: Ansible for Site Reliability Engineering: SRE Practices with Automation

Install the Collection

ansible-galaxy collection install servicenow.itsm

# Python dependency pip install pysnow

Authentication

# Environment variables (recommended)
# export SN_HOST=https://myorg.service-now.com
# export SN_USERNAME=ansible_svc
# export SN_PASSWORD=SecurePass123!

# Or in playbook - name: ServiceNow tasks servicenow.itsm.incident: instance: host: https://myorg.service-now.com username: "{{ vault_snow_user }}" password: "{{ vault_snow_pass }}"

See also: Ansible GitOps: Infrastructure as Code with Git Workflows and AAP

Automated Change Management

Create Change Request Before Deployment

---
- name: Automated change management workflow
  hosts: localhost
  connection: local
  vars:
    change_description: "Deploy webapp v2.5.0 to production"
  tasks:
    - name: Create change request
      servicenow.itsm.change_request:
        state: new
        type: normal
        short_description: "{{ change_description }}"
        description: |
          Automated deployment of webapp v2.5.0
          - Update container image
          - Run database migrations
          - Verify health checks
        priority: moderate
        risk: moderate
        impact: medium
        category: Software
        assignment_group: Platform Engineering
        requested_by: ansible_automation
      register: change_ticket

- name: Log change request number ansible.builtin.debug: msg: "Created change request: {{ change_ticket.record.number }}"

- name: Move to implementation servicenow.itsm.change_request: number: "{{ change_ticket.record.number }}" state: implement

- name: Store ticket number for later ansible.builtin.set_fact: snow_change_number: "{{ change_ticket.record.number }}"

Execute Deployment

- name: Deploy application
  hosts: webservers
  become: true
  tasks:
    - name: Update application
      ansible.builtin.docker_container:
        name: webapp
        image: "registry.example.com/webapp:v2.5.0"
        state: started
        restart_policy: always
      register: deploy_result

- name: Run health check ansible.builtin.uri: url: "http://{{ inventory_hostname }}:8080/health" return_content: true register: health retries: 5 delay: 10 until: health.status == 200

Close Change Request

- name: Close change request
  hosts: localhost
  tasks:
    - name: Update change request
      servicenow.itsm.change_request:
        number: "{{ snow_change_number }}"
        state: review
        close_code: successful
        close_notes: |
          Deployment completed successfully.
          All health checks passed.
          Deployed to {{ groups['webservers'] | length }} servers.

Incident Management

Auto-Create Incidents

- name: Create incident from monitoring alert
  servicenow.itsm.incident:
    state: new
    short_description: "High CPU on {{ alert_host }}"
    description: |
      Monitoring alert: CPU usage above 95% for 10 minutes
      Host: {{ alert_host }}
      Current value: {{ alert_value }}%
      Threshold: 95%
    urgency: high
    impact: medium
    category: Hardware
    subcategory: CPU
    assignment_group: Infrastructure Team
    caller: monitoring_system
  register: incident

Auto-Remediate and Close

- name: Automated incident remediation
  hosts: "{{ alert_host }}"
  become: true
  tasks:
    - name: Identify top CPU process
      ansible.builtin.shell: ps aux --sort=-%cpu | head -5
      register: top_procs

- name: Restart runaway service ansible.builtin.systemd: name: "{{ runaway_service }}" state: restarted when: runaway_service is defined

- name: Verify CPU normalized ansible.builtin.shell: cat /proc/loadavg | awk '{print $1}' register: load until: load.stdout | float < 2.0 retries: 6 delay: 30

- name: Update incident hosts: localhost tasks: - name: Add work notes servicenow.itsm.incident: number: "{{ incident.record.number }}" state: resolved work_notes: | Automated remediation completed: - Restarted {{ runaway_service }} - CPU load normalized to {{ load.stdout }} - Top processes before fix: {{ top_procs.stdout }} close_code: Solved (Permanently) close_notes: "Auto-remediated by Ansible"

See also: Ansible vs GitHub Actions: Key Differences & When to Use Each (2026)

CMDB Updates

Sync Infrastructure to CMDB

- name: Update CMDB from Ansible facts
  hosts: all
  tasks:
    - name: Gather facts
      ansible.builtin.setup:

- name: Update server CI in CMDB servicenow.itsm.configuration_item: name: "{{ inventory_hostname }}" sys_class_name: cmdb_ci_linux_server ip_address: "{{ ansible_default_ipv4.address }}" os: "{{ ansible_distribution }} {{ ansible_distribution_version }}" os_version: "{{ ansible_kernel }}" cpu_count: "{{ ansible_processor_vcpus }}" ram: "{{ ansible_memtotal_mb }}" serial_number: "{{ ansible_product_serial | default('N/A') }}" environment: "{{ env | default('production') }}" category: Server assigned_to: Platform Engineering delegate_to: localhost

Track Relationships

    - name: Create CI relationship (app depends on server)
      servicenow.itsm.configuration_item_batch:
        sys_class_name: cmdb_ci_linux_server
        dataset:
          - name: "{{ inventory_hostname }}"
            relationships:
              - type: Depends on::Used by
                target:
                  name: "webapp-production"
                  sys_class_name: cmdb_ci_service
      delegate_to: localhost

Query ServiceNow

    - name: Get all open incidents for our team
      servicenow.itsm.incident_info:
        query:
          - assignment_group: = Platform Engineering
            state: != resolved
      register: open_incidents

- name: Display open incidents ansible.builtin.debug: msg: "{{ item.number }}: {{ item.short_description }} ({{ item.priority }})" loop: "{{ open_incidents.records }}"

- name: Get pending changes servicenow.itsm.change_request_info: query: - state: = scheduled assignment_group: = Platform Engineering register: pending_changes

Full ITSM Workflow in AAP

# AAP Workflow Template: Production Deployment
#
# ┌──────────────┐    ┌──────────────┐    ┌──────────────┐
# │ Create SNOW  │───→│  Pre-checks  │───→│   Deploy     │
# │ Change Req   │    │  (staging)   │    │  (production)│
# └──────────────┘    └──────────────┘    └──────────────┘
#                           │                     │
#                     ┌─────┴─────┐         ┌─────┴─────┐
#                     │  Failed?  │         │  Failed?  │
#                     │  Cancel   │         │  Rollback │
#                     │  ticket   │         │  + ticket │
#                     └───────────┘         └───────────┘
#                                                 │
#                                           ┌─────┴─────┐
#                                           │ Update    │
#                                           │ CMDB +    │
#                                           │ Close CR  │
#                                           └───────────┘

Best Practices

Service account with minimum permissions — Only ITSM tables needed for automation Always create change requests — Even for automated deployments; maintains audit trail Auto-close on success — But leave incidents open on failure for human review CMDB sync on schedule — Run nightly to keep asset data fresh Use AAP workflow templates — Orchestrate SNOW + deployment + validation in one flow Template-based tickets — Standardize change request descriptions for consistency Work notes, not comments — Use work notes for technical details (internal); comments for user-facing Test against developer instance — ServiceNow offers free developer instances for testing

FAQ

Can I auto-approve change requests?

Yes, for standard (pre-approved) changes. Normal changes should go through the approval workflow in ServiceNow. Configure auto-approval rules in ServiceNow for low-risk, routine changes.

How to handle approval wait?

Use AAP workflow approval nodes — the workflow pauses until a ServiceNow approval callback triggers continuation.

What about ServiceNow Tokyo/Utah/Vancouver?

The servicenow.itsm collection supports all recent ServiceNow releases. API compatibility is maintained across versions.

Conclusion

Integrating Ansible with ServiceNow automates the entire ITSM lifecycle — from change request creation through deployment execution to CMDB updates and incident resolution. This eliminates manual ticket handling, ensures compliance with change management processes, and provides a complete audit trail for every infrastructure change.

Related Articles

Ansible Automation Platform RBACAnsible GitOps with AAPAnsible Compliance Automation

Category: installation

Browse all Ansible tutorials · AnsiblePilot Home