Searching for key in a list of dicts in Ansible [d

2019-07-17 15:11发布

This question already has an answer here:

I've got a list of dictionary that looks similar to the following:

"subnets": [
        {
            "name": "subnet1-name34554",
            "address": "192.168.1.100"
            "id: "id1"
        },
        {
            "name": "subnet2-name67678",
            "addr": "192.168.1.200"
            "id":   "id2"
        },
        {
            "name": "subnet3-name23345",
            "addr": "192.168.1.300"
            "id":   "id3"
        }
    ]

I'm trying to search the dicts with a partial name and return the full name. E.g searching with subnet1 should return subnet1-name34554

If I do something like:

- name: test
  debug: msg="{{ subnets |  selectattr("name", "search", "subnet1") | list  }}"

I get a list with a single dict back:

 [
   {
     "name": "subnet1-name34554",
     "address": "192.168.1.100"
     "id: "id1"
    }
 ]

I'm unsure what the next step to pull just the "name" key is, or if there is a better approach?

1条回答
Ridiculous、
2楼-- · 2019-07-17 15:53

You get list of dicts (single dict) as a result.

So feed it into first filter to get only first element and then address name property.

- name: test
  debug:
    msg: "{{ (subnets |  selectattr('name', 'search', 'subnet1') | list | first).name }}"
查看更多
登录 后发表回答