0

I have a task that checks the redis service status on the host list below

- hosts: 192.168.0.1, 192.168.0.2, 192.168.0.3
  tasks:
    - command:
        cmd: service redis-server status
      register: result
    - debug:
        var: result

After checking I need to access hosts where service does not exist.

And they should be accessible as variable to proceed with them in the next tasks.

Can someone please help?

Disbalance
  • 63
  • 1
  • 7

2 Answers2

1

Similar to Ansible facts it is also possible to gather service_facts. In example

- name: Set facts SERVICE
  set_fact:
    SERVICE: "redis-server.service"

- name: Gathering Service Facts
  service_facts:

- name: Show ansible_facts.services
  debug:
    msg:
      - "{{ ansible_facts.services[SERVICE].status }}"

If you like to perform tasks after on a service of which you don't the status, with Conditionals you can check the state.

If the service is not installed at that time, the specific variable (key) would not be defined. You would perform Conditionals based on variables then

when: ansible_facts.services[SERVICE] is defined
when: ansible_facts.services['redis-server.service'] is defined

Also it is recommend to use the Ansible service module to perform tasks on the service

- name: Start redis-server, if not started
  service:
    name: redis-server
    state: started

instead of using the command module.

Further services related Q&A

U880D
  • 8,601
  • 6
  • 24
  • 40
  • 1
    The answer is great I only add that depending on your ansible_os_family maybe it's better suited to use https://docs.ansible.com/ansible/2.9/modules/systemd_module.html – malpanez Jun 02 '22 at 17:18
1

Finally found the solution that perfectly matches.

- name: Check that redis service exists
       systemd:
         name: "redis"
       register: redis_status
       changed_when: redis_status.status.ActiveState == "inactive"

     - set_fact:
        _dict: "{{ dict(ansible_play_hosts|zip(
                        ansible_play_hosts|map('extract', hostvars, 'redis_status'))) }}"
       run_once: true

     - set_fact:
        _changed: "{{ (_dict|dict2items|json_query('[?value.changed].key'))| join(',') }}"
       run_once: true
Disbalance
  • 63
  • 1
  • 7