Not able to fetch public IP address of virtual machine scale set with Python SDK in Azure

437 views Asked by At

I have a virtual machine scale set and I have two VMs attached to it and I want to fetch its public IP address with the Python SDK.

I am using this script to fetch IP configurations.

def get_vmss_vm_ips():

    # List all network interfaces of the VMSS instance
        vmss_nics = network_client.network_interfaces.list_virtual_machine_scale_set_network_interfaces(
            rg, vmscalesetname)

        niclist = [nic.serialize() for nic in vmss_nics]

        print "IP addresses in the given VM Scale Set:"

        for nic in niclist:
            ipconf = nic['properties']['ipConfigurations']
            print ipconf

This is my output:

{'id': u'/subscriptions/sub_id/resourceGroups/test/providers/Microsoft.Compute/virtualMachineScaleSets/EchoServer/virtualMachines/2/networkInterfaces/test-vnet-nic01/ipConfigurations/test-vnet-nic01-defaultIpConfiguration', 'properties': {'subnet': {'id': u'/subscriptions/sub_id/resourceGroups/test/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/default'}, 'privateIPAddressVersion': u'IPv4', 'publicIPAddress': {'id': u'/subscriptions/sub_id/resourceGroups/test/providers/Microsoft.Compute/virtualMachineScaleSets/EchoServer/virtualMachines/2/networkInterfaces/test-vnet-nic01/ipConfigurations/test-vnet-nic01-defaultIpConfiguration/publicIPAddresses/publicIp-test-vnet-nic01'}, 'privateIPAllocationMethod': u'Dynamic', 'primary': True, 'privateIPAddress': u'10.0.0.9'}, 'name': u'test-vnet-nic01-defaultIpConfiguration'}]

I can see privateIPAddress, but not publicIPAddress. How do I fetch the public IP address?

1

There are 1 answers

0
Jim Xu On

If you want to the Azure scale set virtual machines' public IP address, please refer to the following script

  1. Create a service principal and assign Contributor role to the service principal

    az login
    az ad sp create-for-rbac -n "MyApp" --role contributor \
        --scopes /subscriptions/{SubID} --sdk-auth true
    
  2. Code

    from azure.mgmt.network import NetworkManagementClient
    from azure.identity import ClientSecretCredential
    
    client_id = "<sp appId>"
    secret = "<sp password>"
    tenant = "<sp tenant>"
    Subscription_ID = "<>"
    creds = ClientSecretCredential(
        client_id=client_id, client_secret=secret, tenant_id=tenant)
    
    network_client = NetworkManagementClient(creds, Subscription_ID)
    resource_group_name = "testVm_group"
    virtual_machine_scale_set_name = "testVm"
    results = network_client.public_ip_addresses.list_virtual_machine_scale_set_public_ip_addresses(
        resource_group_name, virtual_machine_scale_set_name)
    
    for result in results:
        print(result.id)
        print(result.ip_address)
    
    

    Enter image description here