From 30ed29ed46c5c3c9cee3769516e335dd61fd2edf Mon Sep 17 00:00:00 2001 From: Charl van Niekerk Date: Tue, 23 Jan 2018 15:14:56 +0100 Subject: [PATCH] Implement the reduce_on_network method to filter a list of IP addresses on a given range. (#34929) (#34930) --- lib/ansible/plugins/filter/ipaddr.py | 34 ++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lib/ansible/plugins/filter/ipaddr.py b/lib/ansible/plugins/filter/ipaddr.py index e27e7c4e3b..a9c1649572 100644 --- a/lib/ansible/plugins/filter/ipaddr.py +++ b/lib/ansible/plugins/filter/ipaddr.py @@ -900,6 +900,39 @@ def network_in_network(value, test): return False +def reduce_on_network(value, network): + ''' + Reduces a list of addresses to only the addresses that match a given network. + + :param: value: The list of addresses to filter on. + :param: network: The network to validate against. + + :return: The reduced list of addresses. + ''' + # normalize network variable into an ipaddr + n = _address_normalizer(network) + + # get first and last addresses as integers to compare value and test; or cathes value when case is /32 + n_first = ipaddr(ipaddr(n, 'network') or ipaddr(n, 'address'), 'int') + n_last = ipaddr(ipaddr(n, 'broadcast') or ipaddr(n, 'address'), 'int') + + # create an empty list to fill and return + r = [] + + for address in value: + # normalize address variables into an ipaddr + a = _address_normalizer(address) + + # get first and last addresses as integers to compare value and test; or cathes value when case is /32 + a_first = ipaddr(ipaddr(a, 'network') or ipaddr(a, 'address'), 'int') + a_last = ipaddr(ipaddr(a, 'broadcast') or ipaddr(a, 'address'), 'int') + + if _range_checker(a_first, n_first, n_last) and _range_checker(a_last, n_first, n_last): + r.append(address) + + return r + + # Returns the SLAAC address within a network for a given HW/MAC address. # Usage: # @@ -1002,6 +1035,7 @@ class FilterModule(object): 'next_nth_usable': next_nth_usable, 'network_in_network': network_in_network, 'network_in_usable': network_in_usable, + 'reduce_on_network': reduce_on_network, 'nthhost': nthhost, 'previous_nth_usable': previous_nth_usable, 'slaac': slaac,