I’ve used the below code to get the Access Token from my Azure account.
https://github.com/AzureAD/azure-activedirectory-library-for-python/blob/dev/sample/certificate_credentials_sample.py
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.
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)
Just to add info to great answer @Charles Xu - here is function with all possible info about VM
Here is my code (thanks Charles Xu - you are my hero):
from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import ServicePrincipalCredentials
from azure.mgmt.compute import ComputeManagementClient
credentials = ServicePrincipalCredentials('XXX', 'YYY', tenant='ZZZ')
client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in client.subscriptions.list()]
for subcription in subs:
subscription_id = subcription.get('subscription_id')
compute_client = ComputeManagementClient(credentials, subscription_id)
vm_list = compute_client.virtual_machines.list_all()
for vm_general in vm_list:
general_view = vm_general.id.split("/")
resource_group = general_view[4]
vm_name = general_view[-1]
vm = compute_client.virtual_machines.get(resource_group, vm_name, expand='instanceView')
print(" osType: ", vm.storage_profile.os_disk.os_type.value)
print(" name: ", vm.name)
print(" type: ", vm.type)
print(" location: ", vm.location)
for stat in vm.instance_view.statuses:
print(" code: ", stat.code)
print('-----------------------------')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With