You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ansible/filter_plugins/net_utils.py

41 lines
1.1 KiB
Python

import ipaddress
from operator import attrgetter
import dns.name
class FilterModule:
def filters(self):
return {
"remove_domain_suffix": remove_domain_suffix,
"ipaddr_sort": ipaddr_sort,
}
def remove_domain_suffix(name):
parent = dns.name.from_text(name).parent()
return parent.to_text()
def ipaddr_sort(addrs, types, unknown_after=True):
check_types = {
"global": attrgetter("is_global"),
"link-local": attrgetter("is_link_local"),
"loopback": attrgetter("is_loopback"),
"multicast": attrgetter("is_multicast"),
"private": attrgetter("is_private"),
"reserved": attrgetter("is_reserved"),
"site_local": attrgetter("is_site_local"),
"unspecified": attrgetter("is_unspecified"),
}
def addr_weight(addr):
if isinstance(addr, str):
addr = ipaddress.ip_address(addr.split("/")[0])
for index, ty in enumerate(types):
if check_types[ty](ipaddress.ip_address(addr)):
return index
return len(types) if unknown_after else -1
return sorted(addrs, key=addr_weight)