Reputation: 346
I am trying to get all the IPs (attached to VMs) from an azure subscription.
I have pulled all the VMs using
compute_client = ComputeManagementClient(credentials, subscription_id)
network_client = NetworkManagementClient(credentials,subscription_id)
for vm in compute_client.virtual_machines.list_all():
print(vm.network_profile.network_interface)
But the network_profile object seems to only be a pointer, I have read through the documentation and can not figure out how to link each vm to its attached IP addresses
I came across this: Is there any python API which can get the IP address (internal or external) of Virtual machine in Azure
But it seems that something has changed.
I am able to resolve the IPs of a machine only if I know the name of the Public_IP address object(Which not all of them have public IPs).
I need to be able to take this network_interface and resolve the IP on it
Upvotes: 4
Views: 7065
Reputation: 346
So It seems that in order to get the IPs, you need to parse the URI given in the vm.network_profile.network_interface
. Then use the the subscription and the nic name to get the IP using network_client.network_interfaces.get()
.
The code I used is below:
compute_client = ComputeManagementClient(credentials, subscription_id)
network_client = NetworkManagementClient(credentials,subscription_id)
try:
get_private(compute_client, network_client)
except:
print("Auth failed on "+ subscription_id)
def get_private(compute_client, network_client):
for vm in compute_client.virtual_machines.list_all():
for interface in vm.network_profile.network_interfaces:
name=" ".join(interface.id.split('/')[-1:])
sub="".join(interface.id.split('/')[4])
try:
thing=network_client.network_interfaces.get(sub, name).ip_configurations
for x in thing:
print(x.private_ip_address)
except:
print("nope")
In this example you could also do x.public_ip_address
to get the public IPs
Upvotes: 7
Reputation: 24138
As your said, indeed, something has changed, but not much.
First as below, NetworkManagementClientConfiguration
has been remove, see the details in the link.
network_client = NetworkManagementClient(credentials,subscription_id)
Second, according to the source code, the parameter public_ip_address_name
is the name of the subnet, cease to be the vm name.
# Resource Group
GROUP_NAME = 'azure-sample-group-virtual-machines'
# Network
SUBNET_NAME = 'azure-sample-subnet'
PUBLIC_IP_NAME = SUBNET_NAME
public_ip_address = network_client.public_ip_addresses.get(GROUP_NAME, PUBLIC_IP_NAME)
Then, you can also the private_ip_address
& public_ip_address
via the IPConfiguration
from the PublicIPAddress
print(public_ip_address.ip_configuration.private_ip_address)
print(public_ip_address.ip_configuration.public_ip_address)
Upvotes: 1