1

I want to filter service statuses of specific services on my Linux nodes, displaying this to whoever is running the playbook. I'm able to bring back all services but this is far too much especially as it will be running on multiple servers. I only need to bring back two or three service statues per server.

I am using the variable in my inventory main_services in other playbooks, and think I should be able to use it for this as well. Just not sure how to get it into json_query?

Here is my inventory file:

[Site1]
AWS-APPA ansible_host=ip-172-33-53-87.eu-west-1.compute.internal main_services='["httpd.service", "postfix.service"]'
AWS-APPB ansible_host=ip-172-33-53-89.eu-west-1.compute.internal main_services='["httpd.service", "postfix.service"]'
AWS-DB01 ansible_host=ip-172-33-29-194.eu-west-1.compute.internal main_services='["mariadb.service", "sshd.service"]'

Here is my current playbook:

- hosts: all
  tasks:
   - name: System services status
     service_facts:
     register: services_running
   - name: Get running services
     set_fact:
       services_runnig: "{{ ansible_facts | json_query('services.* | [?state == `running`].name') }}"

   - name: Services
     debug:
       msg: "{{ services_running }}"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83

1 Answers1

1

This can be achieved with a JMESPath query using the contains function.

Running a query like this:

* | [?
  state == `running` 
  && contains(['httpd.service', 'postfix.service'], name)
].name

On ansible_facts.services will only yield the services httpd and postfix, should they be running.

So, to have is working more dynamically with the value in an inventory you will need to swap the signle and double quotes in your main_services variable:

main_services="['httpd.service', 'postfix.service']"

Then, you will be able to recreate the hardcoded query stated here above:

- debug:
    msg: >-
      {{
        ansible_facts.services | json_query('* | [?
            state == `running`
            && contains(' ~ main_services ~ ', name)
          ].name')
      }}
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
  • Thanks this works, however I only want to see services not running. I have changed to the below. But if all services are running I still get the error text I put in. How can I make it so that only shows if there is a match? `- name: Services debug: msg: "'### Error following services are NOT running ###' {{ ansible_facts.services | json_query('* | [? state != `running` && contains(' ~ main_services ~ ', name) ].name') }}"` – Peter Jackson May 19 '23 at 11:26
  • Add a condition to your `debug` task: `when: ansible_facts.services | json_query('* | [?state != \`running\` && contains(' ~ main_services ~ ', name) ].name') | length` – β.εηοιτ.βε May 19 '23 at 11:38
  • Excellent thanks all working! You have been very helpful @β.εηοιτ.βe – Peter Jackson May 19 '23 at 11:42