Warm tip: This article is reproduced from serverfault.com, please click

ansible json filter list

发布于 2018-04-17 20:59:35

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 :(

Questioner
stevansv
Viewed
0
mromer 2018-04-18 20:02:28

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

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