Use Ansible service_facts to Manage Services Dynamically

Ansible service_facts Module

Managing system services dynamically is a common task in IT automation. The Ansible service_facts module helps you gather detailed information about all services running on a target host. You can then use this data to automate decisions—like restarting stopped services, listing active services, or conditionally applying changes.

In this guide, we’ll explore how to use service_facts effectively through real-world playbook examples and snippet-optimized explanations.

Why Use service_facts?

  • ✅ Dynamically check if services are running or stopped
  • ✅ Make smart decisions without hardcoding service states
  • ✅ Enable conditional service restarts, starts, or checks
  • ✅ Enhance automation in large-scale environments

service_facts stores service data in the ansible_facts.services variable after gathering.

Basic Usage of service_facts Module

Here is a basic playbook example that helps you gather service facts using the service_facts module.

---
- name: Gather service facts
  hosts: webservers
  tasks:
    - name: Collect service information
      service_facts:

This playbook gathers service information from all hosts in the webservers group. The collected facts are stored in the ansible_facts.services dictionary.

Example 1: Check the Status of a Service

In this example, we will check the status of the nginx service using service_facts and when statement.

---
- name: Example of using service_facts
  hosts: all
  become: true
  tasks:
    - name: Gather service facts
      ansible.builtin.service_facts:

    - name: Check if nginx service is running
      debug:
        msg: "Nginx is running"
      when: ansible_facts.services['nginx.service'].state == "running"

Explanation:

  • The service_facts module gathers service information.
  • We use a debug task to print a message if the nginx service is running.

Example 2: Restart a Service if It Is Stopped

This example demonstrates how to restart a service based on its current status.

---
- name: Restart a stopped service
  hosts: all
  become: true
  tasks:
    - name: Gather service facts
      ansible.builtin.service_facts:

    - name: Restart nginx if it is stopped
      ansible.builtin.systemd:
        name: nginx
        state: restarted
      when: ansible_facts.services['nginx.service'].state != "running"

Explanation:

  • This playbook checks the status of nginx and uses the when conditional to restart it only if it is not running.

Example 3: List All Running Services

This playbook lists all running services on the target host.

---
- name: List all running services
  hosts: all
  tasks:
    - name: Gather service facts
      ansible.builtin.service_facts:

    - name: Display running services
      debug:
        var: item
      loop: "{{ ansible_facts.services | dict2items | selectattr('value.state', 'eq', 'running') | list }}"

Explanation:

  • We use dict2items to convert the services dictionary to a list.
  • selectattr filters services that are running, and we display them using the debug module.

Example 4: Ensure a List of Services Are Running

This example shows how to loop through a list of services and ensure they are all running.

---
- name: Ensure multiple services are running
  hosts: all
  become: true
  vars:
    services_list:
      - nginx
      - apache2
  tasks:
    - name: Gather service facts
      ansible.builtin.service_facts:

    - name: Start services if not running
      ansible.builtin.systemd:
        name: "{{ item }}"
        state: started
      loop: "{{ services_list }}"
      when: ansible_facts.services[item + '.service'].state != 'running'

Explanation:

  • We define a list of services (nginx and apache2).
  • For each service, we check if it is running and start it if it is not.

Example 5: Find and Start All Stopped Services

In some cases, you may need to ensure that essential services are not stopped. Instead of checking each service manually, you can automate this process with service_facts module.

In this example, we will gather service facts first. Then, we will identify all services that are currently stopped. Finally, we will start these services automatically.

---
- name: Start all stopped services
  hosts: all
  become: true
  tasks:
    - name: Gather service facts
      ansible.builtin.service_facts:

    - name: List all stopped services
      debug:
        var: item
      loop: "{{ ansible_facts.services | dict2items | selectattr('value.state', 'eq', 'stopped') | list }}"

    - name: Start stopped services
      ansible.builtin.systemd:
        name: "{{ item.key }}"
        state: started
      loop: "{{ ansible_facts.services | dict2items | selectattr('value.state', 'eq', 'stopped') | list }}"
      ignore_errors: true

Here is a brief explanation of the above playbook:

  • The playbook first lists all services that are stopped.
  • It attempts to start each stopped service with a systemd module.
  • If a service is disabled (like firewalld.service), it will skip that service and move on.

Conclusion

The service_facts module makes your Ansible playbooks smarter and more dynamic by providing access to real-time service state. With it, you can:

  • Avoid hardcoding assumptions
  • Conditionally manage services
  • Build resilient and responsive automation

By mastering service_facts, you’ll take your Ansible skills—and your infrastructure reliability—to the next level.

FAQs

1. Is service_facts compatible with all Linux distributions?

Yes, it works with most Linux distributions using systemd, upstart, or init.d service managers.

2. Can I use service_facts to gather information on specific services only?

No, service_facts collects data for all services. However, you can filter the output to focus on specific services.

3. Can I use service_facts in a Windows environment?

No, service_facts is designed for Linux systems with a compatible service manager like systemd.

About Hitesh Jethva

Experienced Technical writer, DevOps professional with a demonstrated history of working in the information technology and services industry. Skilled in Game server hosting, AWS, Jenkins, Ansible, Docker, Kubernetes, Web server, Security, Proxy, Iptables, Linux System Administration, Domain Name System (DNS), and Technical Writing.

View all posts by Hitesh Jethva