Search code examples
ansibleyamljmespathjson-query

ansible json filter list


I'm trying to filter out running services from the output of scan_services module (or service_facts in >= 2.5). The output of this module is something like this:

    "ansible_facts": {
    "services": {
        "NetworkManager-dispatcher.service": {
            "name": "NetworkManager-dispatcher.service",
            "source": "systemd",
            "state": "running"
        },
        "NetworkManager-wait-online.service": {
            "name": "NetworkManager-wait-online.service",
            "source": "systemd",
            "state": "stopped"
        },
        "NetworkManager.service": {
            "name": "NetworkManager.service",
            "source": "systemd",
            "state": "running"
        },

Now, what I'm trying to do is to list only the service names of the ones that are state: running... This code doesn't seems to work at all :/

---
- hosts: all
  tasks:
  - name : Scan current services status
    scan_services:
    register: running_services
  - name: print
    debug: var=item
    with_items: "{{ running_services.|json_query('ansible_facts.services.[?state=='running'].name')}}"

...but I think I'm somewhere near. I guess something is missing in this json_query :(


Solution

  • The jmespath expression returning a list with the name of running services is this :

    ansible_facts.services.* | [?state == `running`].name