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:
JavaScript
x
30
30
1
from azure.mgmt.compute import ComputeManagementClient
2
from azure.common.credentials import ServicePrincipalCredentials
3
4
5
Subscription_Id = "xxxxx"
6
Tenant_Id = "xxxxx"
7
Client_Id = "xxxxx"
8
Secret = "xxxxx"
9
10
credential = ServicePrincipalCredentials(
11
client_id=Client_Id,
12
secret=Secret,
13
tenant=Tenant_Id
14
)
15
16
compute_client = ComputeManagementClient(credential, Subscription_Id)
17
18
vm_list = compute_client.virtual_machines.list_all()
19
# vm_list = compute_client.virtual_machines.list('resource_group_name')
20
i= 0
21
for vm in vm_list:
22
array = vm.id.split("/")
23
resource_group = array[4]
24
vm_name = array[-1]
25
statuses = compute_client.virtual_machines.instance_view(resource_group, vm_name).statuses
26
status = len(statuses) >= 2 and statuses[1]
27
28
if status and status.code == 'PowerState/running':
29
print(vm_name)
30