I have a role task which executes a script to install a systemd user (systemctl --user
) service. I want to add a when
condition to only execute the script when the service is not already installed.
I’m looking for the best solution to do it.
What I’ve tried:
- check with
service
become: yes
become_user: user
ansible.builtin.service:
name: my_service
check_mode: true
register: service_exist
[...]
when: not (service_exist is defined and service_exist | length > 0)
but it doesn’t work, service_exist is always a dict with a lot of information even when the service doesn’t exist and I don’t clearly see what property is different between an existing service and a non-existing one
- check with
systemd_service
andscope: user
become: yes
become_user: user
ansible.builtin.systemd_service:
name: service
state: started
scope: user
check_mode: true
register: systemd_exist
[...]
when: systemd_exist
but this module fails when the service do not exist
fatal: [debian-12]: FAILED! => {"changed": false, "msg": "Could not find the requested service my_fake_service: host"}
Of course, i could simply test the existence of ~$user/.config/systemd/$service.service
file but I would like to do it properly (and not need to retrieve the home directory before testing this)
Any idea?