I’ve used the below code to get the Access Token from my Azure account.
It’s working fine, I already got the token.
However, how can I use this token to list all VMs running in that subscription/resource group with Azure SDK for Python?
I guess that Microsoft documentation is a bit confusing.
Thanks.
Advertisement
Answer
You can use the function list_all()/list() to get all the VMs in the subscription/resource group, but these responses don’t show the VM running status to you. So you also need the function instance_view() to get the VM running status.
Finally, the example code to list all VMs running in that subscription/resource group below:
from azure.mgmt.compute import ComputeManagementClient
from azure.common.credentials import ServicePrincipalCredentials
Subscription_Id = "xxxxx"
Tenant_Id = "xxxxx"
Client_Id = "xxxxx"
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()
# vm_list = compute_client.virtual_machines.list('resource_group_name')
i= 0
for vm in vm_list:
    array = vm.id.split("/")
    resource_group = array[4]
    vm_name = array[-1]
    statuses = compute_client.virtual_machines.instance_view(resource_group, vm_name).statuses
    status = len(statuses) >= 2 and statuses[1]
    if status and status.code == 'PowerState/running':
        print(vm_name)