Search code examples
azureazure-virtual-networkazure-python-sdkazure-public-ip

How to check if Azure public IP is 'associated' via Python SDK


I am trying to get a list of Public IP addresses that are not associated to any azure resource. That is 'orphaned public ip addresses'. I want to know if Azure public IP is 'associated' via Python SDK.

Using the below SDK:

from azure.mgmt.network import NetworkManagementClient
network_client = NetworkManagementClient(credential, SUBSCRIPTION_ID)
public_ip_list = network_client.public_ip_addresses.list_all()

Iterating over 'public_ip_list' will give me all the details regarding IP, but it wont say if it is 'associated' with any azure resource or not.


Solution

  • I am trying to get a list of Public IP addresses that are not associated with any Azure resource

    You can use the below to get both associated and non-associated Public IPs with Azure service using Azure python sdk.

    You can get the public IP that is not associated with Azure resource when you set ip_config to none and also you can get the count of both associated and non-associated IP.

    Code:

    from azure.mgmt.network import NetworkManagementClient
    from azure.identity import DefaultAzureCredential
    
    credential = DefaultAzureCredential()
    Subscription_id="your-subscription-id"
    network_client = NetworkManagementClient(credential,Subscription_id)
    
    public_ip_list = network_client.public_ip_addresses.list_all()
    associated_count = 0
    non_associated_count=0
    for public_ip in public_ip_list:
        if public_ip.ip_configuration is None:
            non_associated_count+=1
            print(f"Public IP address {public_ip.name} is not associated with any Azure resource.")
        else:
            associated_count += 1
            print(f"Public IP address {public_ip.name} is associated with Azure resource {public_ip.ip_configuration.id}.")
    print("Count of Non-associated with resource:",non_associated_count)
    print("Count of associated with resource:",associated_count)
    

    Sample Output:

    Public IP address xxxxxxx is associated with Azure resource /subscriptions/xxxxx/resourceGroups/xxx/providers/Microsoft.Network/networkInterfaces/xxxx/ipConfigurations/primary.
    Public IP address xx is not associated with any Azure resource.
    Count of Non-associated with resource: 26
    Count of associated with resource: 79
    

    enter image description here

    Reference:

    Public IP Addresses - List All - REST API (Azure Virtual Networks) | Microsoft Learn