pythonazureazure-vmazure-rest-api

Azure Python API to check if a VM has public IP


My use-case is:

  1. Identify if a VM has public IP(T/F).
  2. (Optional) Print the Public IP.

I have been trying out a lot of combinations mentioned here and here. My primary goal is to identify if a VM has public IP associated or not. Seems like the azure python sdk has changed over time and some of the old solutions are not working.

I found a simple azure cli command which does the job but I am not able to find the corresponding api for it.

az vm list-ip-addresses --name testVM

Is there an API call that can give the same information. If not, whats the best way to identify if an azure VM has public IP.


Solution

  • I tried to reproduce the same in my environment and got below results:

    I have one Azure VM named srivm with Public IP as below:

    enter image description here

    To fetch this via Python API, I created one service principal with client secret as below:

    enter image description here

    I tried using below code to get Public IP address of virtual machine and got it successfully:

    from azure.identity import ClientSecretCredential
    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.network import NetworkManagementClient
    credential = ClientSecretCredential(
        tenant_id=<tenantID>,  #Your TenantID
        client_id=<appID>,     #Your AppID
        client_secret=<secret>    #Your Client Secret Value
    )
    compute_client = ComputeManagementClient(
        credential=credential,
        subscription_id=<subscriptionID> #Your SubscriptionID
    )
    network_client = NetworkManagementClient(
        credential=credential,
        subscription_id=<subscriptionID> #Your SubscriptionID
        )
    
    rg = 'sri'     #Resource group name
    publicip = 'xxxxxxxxx'   #Subnet name
    result_get = network_client.public_ip_addresses.get(
           rg, publicip
        )
    print(result_get.ip_address)
    

    Response:

    enter image description here

    You can try using the same code in your environment in order to fetch the Public IP of virtual machine.

    Make sure to install required modules and assign required role to the service principal before running the code.