Using ipaddr filter to compare ip address with_items in group_vars

258 views
Skip to first unread message

Dayton Jones

unread,
Oct 20, 2016, 12:02:19 PM10/20/16
to Ansible Project
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)



Łukasz Górski

unread,
Oct 20, 2016, 1:00:46 PM10/20/16
to ansible...@googlegroups.com
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') | 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.

--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-project+unsubscribe@googlegroups.com.
To post to this group, send email to ansible-project@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/b8d1f3ec-a0af-4a30-a4c7-06e08a715781%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Łukasz Górski
Administrator Systemu Linux
e-mail: l.go...@trojmiasto.pl

Tel. 058 321 95 65 Kom.
Moje miasto to Trójmiasto!

Trojmiasto.pl Sp. z o.o. ul. Wały Piastowskie 1, 80-855 Gdańsk
tel: 58 321-95-00 fax: 58 321-95-13 e-mail: in...@trojmiasto.pl
NIP 583-30-12-490, REGON 220563678
Sąd Rejonowy Gdańsk-Północ w Gdańsku, VII Wydział Gospodarczy Krajowego Rejestru Sądowego, KRS 0000300002, Kapitał zakładowy 2 150 000 PLN
fbTrojmiasto.pl na Facebooku. Dołącz do nas!
Reply all
Reply to author
Forward
0 new messages