Python – Azure Classic operations – list all virtual machines #1

Python – Azure Classic operations – list all virtual machines #1

In Azure Classic all virtual machines are located in the “same” place. There is no need to select each region and list VMs.

The documentation about the topic is located here:

http://azure-sdk-for-python.readthedocs.org/en/latest/ref/azure.servicemanagement.models.html

Below code displays all Virtual Machines via Python:

 

from azure.servicemanagement import *

subscription_id = 'XXXXXXXXXXXXXXXXXXXXXXX'
cert_file = 'XXXXXXXXX.pem'

sms = ServiceManagementService(subscription_id, cert_file)

services = sms.list_hosted_services()
count = 0
print("{:<25} {:<20} {:<10} {:<15} {:<25} {:<20}".format("VM name", \
"Status", "Size", "Power state", "Service creation", "Role size"))
for service in services:
    props = sms.get_hosted_service_properties(service.service_name, True)

    for dep in props.deployments.deployments:

        for inst in range(0, len(dep.role_instance_list)):
            iname = dep.role_instance_list[inst].instance_name
            istatus = dep.role_instance_list[inst].instance_status
            isize = dep.role_instance_list[inst].instance_size
            ipower = dep.role_instance_list[inst].power_state
            typ = dep.role_list[inst].role_size
            count += 1
            print("{:<25} {:<20} {:<10} {:<15} {:<25} {:<20}".format(\
                   iname, istatus, isize, ipower, dep.created_time, typ))
print(count)

 

Output:

VM name   Status              Size  Power state   Service creation       Role size 
vm1       StoppedDeallocated        Stopped       2015-03-20T09:41:00Z   Large 
vm2       StoppedDeallocated        Stopped       2015-03-20T09:41:00Z   Large


 

The same with Azure PowerShell:

$vms = Get-AzureVM
$count = 0


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

Leave a Reply