Bootstrap FreeKB - Ansible - Gather service and systemd facts using service_facts
Ansible - Gather service and systemd facts using service_facts

Updated:   |  Ansible articles

service_facts can be used to gather the list of services on a target system.

---
- hosts: localhost
  tasks:
  - name: gather service facts
    ansible.builtin.service_facts:

  - debug:
      var: ansible_facts.services
...

 

Something like this should be returned.

ok: [localhost] => {
    "ansible_facts.services": {
        "NetworkManager.service": {
            "name": "NetworkManager.service",
            "source": "systemd",
            "state": "running",
            "status": "enabled"
        },
        "nginx.service": {
            "name": "nginx.service",
            "source": "systemd",
            "state": "stopped",
            "status": "enabled"
        }
    }
}

 

Often, you are going to want to return the dictionary of a particular service.

---
- hosts: localhost
  tasks:
  - name: gather service facts
    ansible.builtin.service_facts:

  - debug:
      var: ansible_facts.services['sshd.service']
...

 

Which should return something like this.

ok: [localhost] => {
    "ansible_facts.services['sshd.service']": {
        "name": "sshd.service",
        "source": "systemd",
        "state": "running",
        "status": "enabled"
    }
}

 

This is often great to couple in with the systemd service to only do something when the service exists.

---
- hosts: localhost
  tasks:
  - name: gather service facts
    ansible.builtin.service_facts:

  - name: stop nginx
    systemd:
      name: nginx
      state: stopped
      enabled: no
    when: ansible_facts.services['nginx.service'] is defined and ansible_facts.services['nginx.service'].state != 'stopped'
...

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 1b7c41 in the box below so that we can be sure you are a human.