net_utils: add miscellaneous Jinja2 filters

This commit is contained in:
jeltz 2022-08-19 04:57:27 +02:00
parent 126d0f49df
commit c775a48ca8
Signed by: jeltz
GPG key ID: 800882B66C0C3326

View file

@ -0,0 +1,28 @@
import ipaddress
import dns.name
class FilterModule:
def filters(self):
return {
"add_origin": add_origin,
"add_origin_keys": add_origin_keys,
"ip_filter": ip_filter,
}
def ip_filter(addresses, networks):
if isinstance(addresses, dict):
return {k: ip_filter(v, networks) for k, v in addresses.items()}
ip_networks = [ipaddress.ip_network(n) for n in networks]
ip_addresses = [ipaddress.ip_address(a) for a in addresses]
return [str(a) for a in ip_addresses if any(a in n for n in ip_networks)]
def add_origin(name, origin="."):
return dns.name.from_text(name, dns.name.from_text(origin)).to_text()
def add_origin_keys(dct, origin="."):
return {add_origin(k, origin): v for k, v in dct.items()}