Get rid of the extension .service
. For example, put the below declarations into the group_vars
shell> cat group_vars/all/my_services.yml
my_keys: "{{ ansible_facts.services.keys()|
map('reverse')|
map('split', '.', 1)|
map('last')|
map('reverse') }}"
my_services: "{{ dict(my_keys|zip(ansible_facts.services.values())) }}"
gives
my_services:
ModemManager:
name: ModemManager.service
source: systemd
state: inactive
status: disabled
NetworkManager:
name: NetworkManager.service
source: systemd
state: stopped
status: masked
...
Given the variable
component: ssh
Both getting the facts and testing the state are simpler. The code is cleaner.
- debug:
var: my_services[component]
gives
my_services[component]:
name: ssh.service
source: systemd
state: running
status: enabled
and
- debug:
msg: "{{ component }} is running"
when: my_services[component].state == 'running'
gives
msg: ssh is running
Example of a complete playbook for testing
shell> cat pb.yml
- hosts: localhost
vars:
component: ssh
tasks:
- ansible.builtin.service_facts:
- debug:
var: my_services
when: debug|d(false)|bool
- debug:
var: my_services[component]
- debug:
msg: "{{ component }} is running"
when: my_services[component].state == 'running'