mirror of
https://github.com/ansible-collections/community.general.git
synced 2025-06-26 10:10:22 -07:00
Add cidr_merge filter (#36081)
This commit is contained in:
parent
bf53e441b1
commit
e2c1589201
3 changed files with 73 additions and 1 deletions
|
@ -413,6 +413,38 @@ def _win_query(v):
|
|||
|
||||
|
||||
# ---- IP address and network filters ----
|
||||
|
||||
# Returns a minified list of subnets or a single subnet that spans all of
|
||||
# the inputs.
|
||||
def cidr_merge(value, action='merge'):
|
||||
if not hasattr(value, '__iter__'):
|
||||
raise errors.AnsibleFilterError('cidr_merge: expected iterable, got ' + repr(value))
|
||||
|
||||
if action == 'merge':
|
||||
try:
|
||||
return [str(ip) for ip in netaddr.cidr_merge(value)]
|
||||
except Exception as e:
|
||||
raise errors.AnsibleFilterError('cidr_merge: error in netaddr:\n%s' % e)
|
||||
|
||||
elif action == 'span':
|
||||
# spanning_cidr needs at least two values
|
||||
if len(value) == 0:
|
||||
return None
|
||||
elif len(value) == 1:
|
||||
try:
|
||||
return str(netaddr.IPNetwork(value[0]))
|
||||
except Exception as e:
|
||||
raise errors.AnsibleFilterError('cidr_merge: error in netaddr:\n%s' % e)
|
||||
else:
|
||||
try:
|
||||
return str(netaddr.spanning_cidr(value))
|
||||
except Exception as e:
|
||||
raise errors.AnsibleFilterError('cidr_merge: error in netaddr:\n%s' % e)
|
||||
|
||||
else:
|
||||
raise errors.AnsibleFilterError("cidr_merge: invalid action '%s'" % action)
|
||||
|
||||
|
||||
def ipaddr(value, query='', version=False, alias='ipaddr'):
|
||||
''' Check if string is an IP address or network and filter it '''
|
||||
|
||||
|
@ -1026,6 +1058,7 @@ class FilterModule(object):
|
|||
''' IP address and network manipulation filters '''
|
||||
filter_map = {
|
||||
# IP addresses and networks
|
||||
'cidr_merge': cidr_merge,
|
||||
'ipaddr': ipaddr,
|
||||
'ipwrap': ipwrap,
|
||||
'ip4_hex': ip4_hex,
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue