Python – Azure Resource Manager operations – list all virtual machines #1

Python – Azure Resource Manager operations – list all virtual machines #1

Azure Resource manager is completely different than Azure Classic. The same is with python sdk for Azure classic and RM.
Here is the exemple how to list all virtual machines in Azure RM using python:

 

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.compute import *
from azure.mgmt.resource.resources import ResourceManagementClient,\
ResourceManagementClientConfiguration

subscription_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
tenant = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

def get_credentials():
    return ServicePrincipalCredentials(
        client_id=client_id,
        secret=secret,
        tenant=tenant,
    )

def get_compute():
    return ComputeManagementClient(ComputeManagementClientConfiguration(
        get_credentials(),
        subscription_id
    ))

def get_resource():
    return ResourceManagementClient(
    ResourceManagementClientConfiguration(
        get_credentials(),
        subscription_id
    )
)

def main():
    
    print("{:<20} {:<20}".format("Resoruce Group", "VM name"))
    res = get_resource()
    resource_groups = res.resource_groups.list()
    for group in resource_groups:

        com = get_compute()
        vms = com.virtual_machines
        for vm in vms.list(resource_group_name=group.name):
            print("{:<20} {:<20}".format(group.name, vm.name))

if __name__ == '__main__':
    main()

 

Output:

Resoruce Group       VM name             
CentRes2             vmcent1             
MyResGrp             vmcent2      

The same action using PowerShell:

Note: First login to Azure RM using command Add-AzureRmAccount.

$vms = Get-AzureRmVM
$count = 0

foreach($vm in $vms)
	{
	$count++
	Write-Host $vm.name
	}
Write-Host "Count: " $count

Leave a Reply