def main(): module = AnsibleModule(argument_spec=dict(subnet=dict(), )) subnet = module.params['subnet'] if subnet is not None: split_addr = subnet.split('/') if len(split_addr) != 2: module.fail_json( "Invalid CIDR notation: expected a subnet mask (e.g. 10.0.0.0/32)" ) module.exit_json(resolved=to_subnet(split_addr[0], split_addr[1]))
def validate_ip(module, cidr_ip): split_addr = cidr_ip.split('/') if len(split_addr) == 2: # this_ip is a IPv4 or IPv6 CIDR that may or may not have host bits set # Get the network bits. try: ip = to_subnet(split_addr[0], split_addr[1]) except ValueError: ip = to_ipv6_subnet(split_addr[0]) + "/" + split_addr[1] if ip != cidr_ip: module.warn("One of your CIDR addresses ({0}) has host bits set. To get rid of this warning, " "check the network mask and make sure that only network bits are set: {1}.".format(cidr_ip, ip)) return ip return cidr_ip
def get_cidr_network_bits(module, cidr_block): fixed_cidrs = [] for cidr in cidr_block: split_addr = cidr.split('/') if len(split_addr) == 2: # this_ip is a IPv4 CIDR that may or may not have host bits set # Get the network bits. valid_cidr = to_subnet(split_addr[0], split_addr[1]) if cidr != valid_cidr: module.warn("One of your CIDR addresses ({0}) has host bits set. To get rid of this warning, " "check the network mask and make sure that only network bits are set: {1}.".format(cidr, valid_cidr)) fixed_cidrs.append(valid_cidr) else: # let AWS handle invalid CIDRs fixed_cidrs.append(cidr) return fixed_cidrs
def test_to_subnet_invalid(): with pytest.raises(ValueError): to_subnet('foo', 'bar')
def test_to_subnet(): result = to_subnet('192.168.1.1', 24) assert '192.168.1.0/24' == result result = to_subnet('192.168.1.1', 24, dotted_notation=True) assert '192.168.1.0 255.255.255.0' == result
def test_to_subnet_invalid(): with pytest.raises(ValueError): to_subnet("foo", "bar")
def test_to_subnet(): result = to_subnet("192.168.1.1", 24) assert "192.168.1.0/24" == result result = to_subnet("192.168.1.1", 24, dotted_notation=True) assert "192.168.1.0 255.255.255.0" == result