2

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.

tscomitre
  • 33
  • 1
  • 6

4 Answers4

6

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)
Charles Xu
  • 29,862
  • 2
  • 22
  • 39
  • That's cool @Charles however, I don't have Secret for AuthN, only Certificate instead. – tscomitre Nov 19 '19 at 04:20
  • @tscomitre Well, it doesn't matter using the different auth ways. It's the code to get the running VMs. The answer you add only gets the VMs and not all the VMs are in the running state. – Charles Xu Nov 19 '19 at 06:05
  • Thanks for that mate, that worked perfect. I've just changed the AuthN method and had run your code. – tscomitre Nov 19 '19 at 22:05
2

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('-----------------------------')
Donets
  • 63
  • 10
1

I got it sorted by using the following codes.

Getting the Token by using this sample code from MS:

certificate_credentials_sample.py

Then adding the following lines:

from msrestazure.azure_active_directory import AADTokenCredentials
from azure.mgmt.compute import ComputeManagementClient

client_id = 'XXXXXXXXXXXXX'

credentials = AADTokenCredentials(token, client_id)

compute_client = ComputeManagementClient(credentials, subscription_id)

resourceGroup = 'XXXXXXXXXXXX'
for vm in compute_client.virtual_machines.list(resourceGroup):
    print(vm)

The parameters.json

{
    "resource" : "https://management.azure.com",
    "tenant" : "XXXXXXXXXXXXXXXXXXXX",
    "authorityHostUrl" : "https://login.microsoftonline.com",
    "clientId" : "XXXXXXXXXXXXXXXXXXXX",
    "thumbprint" : "XXXXXXXXXXXXXXXXXXXX",
    "privateKeyFile" : "XXXXXXXXXXXXXXXXXXXX.pem"
}
tscomitre
  • 33
  • 1
  • 6
0

You need to list VM instances and ScaleSets for a complete list

The list_all()/list() methods are not listing VMs in a ScaleSet AFAIK. The solution I found:

  1. Iterate the Resource Groups
  2. List the VMs and ScaleSets
  3. Iterate the VMs in a ScaleSet if exists
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.resource import ResourceManagementClient
from azure.common.credentials import ServicePrincipalCredentials

subscription_id = 'XXXX'
tenant_id = 'XXXX'
client_id = 'XXXX'
client_secret = 'XXXX'

credentials = ServicePrincipalCredentials(tenant=tenant_id, client_id=client_id, secret=client_secret)
resource_client = ResourceManagementClient(credentials, subscription_id)
compute_client = ComputeManagementClient(credentials, subscription_id)

def list_vms_in_subscription():
    group_list = resource_client.resource_groups.list()
    for group in list(group_list):
        list_vms_in_groups(group.name)

def list_vms_in_groups(group_name):
    for resource in resource_client.resources.list_by_resource_group(group_name):
        if resource.type == "Microsoft.Compute/virtualMachines":
            print(resource.name)

        if resource.type == "Microsoft.Compute/virtualMachineScaleSets":
            vmss = compute_client.virtual_machine_scale_set_vms.list(group_name, resource.name)
            for vm in vmss:
                print(vm.name)


if __name__ == '__main__':
    list_vms_in_subscription()
Alon Lavian
  • 1,149
  • 13
  • 14