Printing list of Virtual Machines

Viewed 246

I want to list down my vms on my azure. This code is running correctly but the I am getting output in the form of object address. how to convert this object address to readable information. the ouput is <azure.mgmt.compute.v2019_03_01.models.virtual_machine_paged.VirtualMachinePaged object at 0x00000200D5C49E50>

from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials


Subscription_Id = "XXXXXX"
Tenant_Id = "XXXX"
Client_Id = "XXXX"
Secret = "XXXXX"

credential = ServicePrincipalCredentials(
    client_id=Client_Id,
    secret=Secret,
    tenant=Tenant_Id
)

compute_client = ComputeManagementClient(credential, Subscription_Id)

vm_list = compute_client.virtual_machines.list_all()
print(vm_list)
1 Answers

The VM list all returns a result of Paged values. So , in order to print all the VM's you will need to use by_page or next.

Another issue is <azure.common.credentials><ServicePrincipalCredentials> doesn't have get_token , so while retrieving the paged values will error out in authentication failed. To avoid this , you can use <azure.identity><ClientSecretCredentails> which is the same as Service Principal Credentials.

I tested applying the above solutions to your code in my environment as below:

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import ClientSecretCredential


Subscription_Id = "xxxx"
Tenant_Id = "xxxx"
Client_Id = "xxxxx"
Secret = "xxxxx"

credential = ClientSecretCredential(
    client_id=Client_Id,
    client_secret=Secret,
    tenant_id=Tenant_Id
)

compute_client = ComputeManagementClient(credential, Subscription_Id)

vm_list = compute_client.virtual_machines.list_all()
pageobject1=vm_list.by_page(continuation_token=None)
for page in pageobject1:
    for j in page:
        print(j)

Output:

enter image description here

Note: If you want to expand network_profile, diagnostics_profile etc. then you can add them in the same for loop like below:

vm_list = compute_client.virtual_machines.list_all()

pageobject1=vm_list.by_page(continuation_token=None)
for page in pageobject1:
    for j in page:
        network_profile=j.network_profile
        hardware_profile=j.hardware_profile
        print("VM Details : ", j)
        print("Network Profile : ", network_profile)
        print("Hardware Profile : " , hardware_profile)

Output:

enter image description here

Related