Search code examples
pythonazurediskazure-cli

Get a list of Azure OS Disks attached to VMs in specific subscription


I am fetching a list of OS Disks attached to VMs in Azure in all resource groups of specific subscription. I found a AZ utility to fetch the list in json format.

Using below sequence I am able to get the list in json format, Is there any similar way to get this achieved using any python module ?

az login
az account set --subscription <subscription>
az disk list

Solution

  • Yes, it is possible. You could use method list to get disks in your subscription.

    For example:

    from azure.common.credentials import ServicePrincipalCredentials
    from azure.mgmt.compute import ComputeManagementClient
    from azure.mgmt.resource import ResourceManagementClient, SubscriptionClient
    
    # Tenant ID for your Azure Subscription
    TENANT_ID = ''
    
    # Your Service Principal App ID
    CLIENT = ''
    
    # Your Service Principal Password
    KEY = ''
    
    credentials = ServicePrincipalCredentials(
        client_id = CLIENT,
        secret = KEY,
        tenant = TENANT_ID
    )
    
    subscription_id = ''
    
    compute_client = ComputeManagementClient(credentials, subscription_id)
    
    disks = compute_client.disks.list()
    for disk in disks:
        print disk
    

    Note: It will return all disks in your subscription. But it is possible some disks are not OS disk, they maybe Data disk or a disk that not attach for a VM.