Search code examples
ansibleansible-facts

How to list only the running services with ansible_facts


How to list all the services of a system with state=='running' without providing a list like the first code?

- name: Populate service facts
  service_facts:
  no_log: true
  register: inspect_services2
  when: "ansible_facts.services[] is defined and ansible_facts.services[].state == 'running' "

I have manage to list them only if I use a list:

- name: Running Services 
  debug:
    msg: "{{ ansible_facts.services[item].state == 'running' }}"
  when: "ansible_facts.services[item] is defined and ansible_facts.services[item].state == 'running' "
  loop: "{{ inspect_services2 }}"
  ignore_errors: yes

Solution

  • In a nutshell:

    ---
    - name: work with service facts
      hosts: localhost
    
      tasks:
        - name: gather service facts
          service_facts:
    
        - name: show running services
          debug:
            msg: "{{ ansible_facts.services | dict2items 
              | selectattr('value.state', '==', 'running') | items2dict }}"
    

    This gives you a dict with all info for all running services. If e.g. you only want to display the names of those services, your could change the message in debug task to:

            msg: "{{ ansible_facts.services | dict2items 
              | selectattr('value.state', '==', 'running') | map(attribute='key') }}"
    

    You are of course absolutely free to use that result and put it in a variable somewhere as an alias to reuse it. Below a useless yet functional example creating a file with the service name on the target server just to illustrate:

    ---
    - name: Work with service facts II
      hosts: localhost
    
      vars:
        # Note1: this will be undefined until service facts are gathered
        # Note2: this time this var will be a list of all dicts
        # dropping the initial key wich is identical to `name`
        running_services: "{{ ansible_facts.services | dict2items 
          | selectattr('value.state', '==', 'running') | map(attribute='value') }}"
    
      tasks:
        - name: gather service facts
          service_facts:
    
        - name: useless task creating a file with service name in tmp
          copy:
            content: "ho yeah. {{ item.name }} is running"
            dest: "/tmp/{{ item.name }}.txt"
          loop: "{{ running_services }}"