Ansible - Gather service and systemd facts using service_facts
by
Jeremy Canfield |
Updated: September 08 2023
| 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