Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching for key in a list of dicts in Ansible [duplicate]

Tags:

ansible

jinja2

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?

like image 709
Setanta Avatar asked Jan 29 '23 19:01

Setanta


1 Answers

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 }}"
like image 160
Konstantin Suvorov Avatar answered Mar 15 '23 22:03

Konstantin Suvorov