# Using ipaddr filter to compare ip address with\_items in group\_vars

**URL:** <https://forum.ansible.com/t/using-ipaddr-filter-to-compare-ip-address-with-items-in-group-vars/22844>\
**Category:** Ansible Project\
**Created:** [October 20, 2016, 4:02pm UTC](https://forum.ansible.com/t/using-ipaddr-filter-to-compare-ip-address-with-items-in-group-vars/22844 "2016-10-20T16:02:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dayton\_Jones](https://avatars.discourse-cdn.com/v4/letter/d/22d042/32.png) [@Dayton\_Jones](https://forum.ansible.com/u/Dayton_Jones)\
**Post date:** [October 20, 2016, 4:02pm UTC](https://forum.ansible.com/t/using-ipaddr-filter-to-compare-ip-address-with-items-in-group-vars/22844/1 "2016-10-20T16:02:19Z")

</div>

Ok, given the following group\_vars:

> iloms:
> 
> - gateway: 10.224.64.1  
> mask: 255.255.248.0
> - gateway: 10.85.0.1  
> mask: 255.255.254.0

and an ip from a lookup:

> ilom\_ip: “{{ lookup(‘dig’, ‘mgmt-’ + ansible\_local.system\_facts.host\_serial + ‘.example.com’) }}”

I need to compare ilom\_ip to {{ item.gateway }}/{{ item.mask }} and if it is in the same subnet, use those values (and if not, test the next, etc)

I know I can concatenate the gw and mask:

ilom\_net = ‘{{ item.gateway }}/{{ item.mask }}’

> with\_items: iloms

and that I can test if ilom\_ip is in the same subnet as ilom\_net with:

> {{ ilom\_ip | ipaddr(ilom\_net) }}

But how do I combine these into a task and reliably get the correct gw/mask to use in additional tasks (setting ip/gw/netmask on on ilom)

---

<div class="post-metadata">

**Author:** ![Lukasz\_Gorski](https://avatars.discourse-cdn.com/v4/letter/l/5f9b8f/32.png) [@Lukasz\_Gorski](https://forum.ansible.com/u/Lukasz_Gorski)\
**Post date:** [October 20, 2016, 4:17pm UTC](https://forum.ansible.com/t/using-ipaddr-filter-to-compare-ip-address-with-items-in-group-vars/22844/2 "2016-10-20T16:17:04Z")

</div>

I encountered a similar issue and managed to solve it by creating a simple filter plugin:

def ip\_in\_net(list, net):  
from netaddr import IPAddress, IPNetwork  
return [ip for ip in list if IPAddress(ip) in IPNetwork(net)]

class FilterModule(object):  
def filters(self):  
return {  
‘ip\_in\_net’: ip\_in\_net  
}

and then use it like that:

ip: “{{ ansible\_all\_ipv4\_addresses | ip\_in\_net(‘[172.16.0.0/24](http://172.16.0.0/24)’) | first }}”

Now this obviously does not work with your data, and requires a ‘netaddr’ Python package (apt-get install python-netaddr in my Ubuntu 14.04), but quite likely you could use the interface provided by that package to suit your needs exactly, it’s very friendly.
