Find variable in dictonary based on a known key:value pair

21 views
Skip to first unread message

Eric Brewer

unread,
Dec 19, 2018, 3:44:26 PM12/19/18
to Ansible Project
So having a dictionary in a var file, how would I find a value, if I don't know the list position, but I do know a value of another key:value pair?


physical_interface_list:
 
- lan: 1
    slave
: no
    route_list
:
     
- ip4: 1.1.1.1
        subnet4
: 2.2.2.2
        gateway4
: 3.3.3.3
        present
: yes
    ip4
: 4.4.4.4
    dev_name
: eth1



So if know that my variable lives somewhere in

physical_interface_list[?]['ip4']

And I know that the dev_name is eth1, how would I go about finding ip4 at the correct array position (assuming there are more than the one I am showing)?  The variable file I am pulling from is enormous, and I have committed the 6 levels above it for brevity's sake.

I have tried using map, but I must not understand how to use it correctly, and the documentation I have been reading doesn't really tell me if it can be used that way.....

Kai Stian Olstad

unread,
Dec 20, 2018, 8:37:13 AM12/20/18
to ansible...@googlegroups.com
{{ (physical_interface_list | selectattr('dev_name', 'eq', 'eth1') | list).0.ip4 }}


--
Kai Stian Olstad


Eric Brewer

unread,
Dec 20, 2018, 9:16:31 AM12/20/18
to Ansible Project
Awesome! Thanks so much, that worked for me, but I had to tweak it just a little bit. I tried using 'eq' as the filter and it threw an error, but 'equalto' didn't give it any problems.  Otherwise this was exactly what I needed!

Kai Stian Olstad

unread,
Dec 20, 2018, 9:27:31 AM12/20/18
to ansible...@googlegroups.com
On Thursday, 20 December 2018 15:16:30 CET Eric Brewer wrote:
>
> Awesome! Thanks so much, that worked for me, but I had to tweak it just a
> little bit. I tried using 'eq' as the filter and it threw an error, but
> 'equalto' didn't give it any problems. Otherwise this was exactly what I
> needed!

eq/equalto is a test not a filter.
In Jinja 2.10 it's called eq and the alias is equalto, but in older version you only have the name equalto.

--
Kai Stian Olstad


Eric Brewer

unread,
Dec 20, 2018, 10:00:31 AM12/20/18
to Ansible Project
Gotcha, I need to work on getting my terminology right, still new at this.  Thanks again!
Reply all
Reply to author
Forward
0 new messages