def _find_network_ip(network_name, reserved_ip_addresses, device=None): """Find the network and IP address to be used for deployment. If ``device`` is specified, re-use an IP of that device that matches the specified network. If no network is specified, any IP matches. If no suitable network is found, ``Network.DoesNotExist`` is raised. If no suitable IP address is found, "" is returned for the IP. Never uses an IP that is in ``reserved_ip_addresses``. When an IP is found, it is added to ``reserved_ip_addresses``. """ if network_name: network = Network.objects.get(name=network_name) if device: for ipaddress in device.ipaddress_set.filter( is_management=False, network=network, ).order_by('hostname', 'address'): ip = ipaddress.address if ip in reserved_ip_addresses: continue reserved_ip_addresses.append(ip) return network, ip ip = get_first_free_ip(network.name, reserved_ip_addresses) or '' if ip: reserved_ip_addresses.append(ip) return network, ip if device: for ipaddress in device.ipaddress_set.filter( is_management=False, ).order_by('hostname', 'address'): ip = ipaddress.address if ip in reserved_ip_addresses: continue try: network = Network.from_ip(ip) except IndexError: continue reserved_ip_addresses.append(ip) return network, ip raise Network.DoesNotExist("No default network for this device")