ansible json filter list

2019-08-20 12:54发布

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

1条回答
Lonely孤独者°
2楼-- · 2019-08-20 13:27

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

ansible_facts.services.* | [?state == `running`].name
查看更多
登录 后发表回答