3
from charmhelpers.fetch import apt_install
4
from charmhelpers.core.hookenv import (
11
apt_install('python-netifaces')
17
apt_install('python-netaddr')
21
def _validate_cidr(network):
23
netaddr.IPNetwork(network)
24
except (netaddr.core.AddrFormatError, ValueError):
25
raise ValueError("Network (%s) is not in CIDR presentation format" %
29
def get_address_in_network(network, fallback=None, fatal=False):
31
Get an IPv4 address within the network from the host.
34
network (str): CIDR presentation format. For example,
36
fallback (str): If no address is found, return fallback.
37
fatal (boolean): If no address is found, fallback is not
38
set and fatal is True then exit(1).
41
def not_found_error_out():
42
log("No IP address found in network: %s" % network,
47
if fallback is not None:
53
_validate_cidr(network)
54
for iface in netifaces.interfaces():
55
addresses = netifaces.ifaddresses(iface)
56
if netifaces.AF_INET in addresses:
57
addr = addresses[netifaces.AF_INET][0]['addr']
58
netmask = addresses[netifaces.AF_INET][0]['netmask']
59
cidr = netaddr.IPNetwork("%s/%s" % (addr, netmask))
60
if cidr in netaddr.IPNetwork(network):
63
if fallback is not None: