skip to Main Content

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?

2

Answers


  1. Chosen as BEST ANSWER

    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
    

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search