Search code examples
pythonazureazure-devopsazure-functionsazure-sdk

how to get public IP of azure scale set instance from python API azure sdk?


I have assigned to each instance public IP (no Load Balancer ), i tried to get it's public IP from the python code but no luck, what i try so far :

from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.network import NetworkManagementClient      
credentials = ServicePrincipalCredentials(client_id=ID, secret=SECRET_KEY, tenant=TENANT_ID)
for net in NetworkManagementClient(credentials, SUBSCRIPTION_ID):
    print net

the IP is not here . i have also tried via scale set object that returned from this :

vmss =  ComputeManagementClient(credentials, SUBSCRIPTION_ID).virtual_machine_scale_set_vms.list(resource_group_name=resource_group,
                                                                           virtual_machine_scale_set_name=scale_set_name)

but i don't see property of public IP in it .


Solution

  • I wasn't sure of this myself so I had a look. Turns out there is an API under the virtual networks service that lists all public IP addresses of a scale set.

    This code should work for you, it'll list all of the public IP addresses in use inside of a scale set.

    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.network import NetworkManagementClient
    
    # Your Azure Subscription ID
    subscription_id = 'xxxx-xxxx-xxxx'
    
    compute_client = ComputeManagementClient(credentials, subscription_id)
    network_client = NetworkManagementClient(credentials, subscription_id)
    
    rg = 'testscaleset-rg'
    scaleset_name = 'testscaleset'
    
    for i, vm in enumerate(compute_client.virtual_machine_scale_set_vms.list(resource_group_name=rg, virtual_machine_scale_set_name=scaleset_name)):
        nic_name = (vm.network_profile.network_interfaces[0].id).split("/")[-1]
        ip_config_name = vm.network_profile_configuration \
                   .network_interface_configurations[0]\
                   .ip_configurations[0]\
                   .name
        ip_address_name = vm.network_profile_configuration \
               .network_interface_configurations[0]\
               .ip_configurations[0]\
               .public_ip_address_configuration\
               .name
        print(vm.name, (network_client.public_ip_addresses.get_virtual_machine_scale_set_public_ip_address( \
            resource_group_name=rg, \
            virtual_machine_scale_set_name=scaleset_name,\
            virtualmachine_index=i, \
            network_interface_name=nic_name, \
            ip_configuration_name=ip_config_name, \
            public_ip_address_name=ip_address_name)).ip_address)
    

    Should return

    testscaleset_0 40.68.133.234