for loop keeps repeating output in python script

102 Views Asked by At

I have written a script to list the VMs in our Azure subscription and I've noticed that the list keeps repeating itself until I cancel the run.

The script is below:

from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential 


subscription_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CREDENTIAL = DefaultAzureCredential(exclude_shared_token_cache_credential=True, exclude_environment_credential=True, exclude_managed_identity_credential=True, exclude_visual_studio_code_credential=True)

compute_client = ComputeManagementClient(CREDENTIAL, subscription_id)

def list_vms_in_subscription():
    group_list = compute_client.resource_skus.list()
    for group in list(group_list):
        list_vms_in_groups(group.name)

def list_vms_in_groups(group_name):
    for resource in compute_client.virtual_machines.list_all():
        if resource.type == "Microsoft.Compute/virtualMachines":
            print(resource.name)

if __name__ == '__main__':
    list_vms_in_subscription()
3

There are 3 best solutions below

1
Aditya Raghav On
from azure.mgmt.compute import ComputeManagementClient
from azure.identity import DefaultAzureCredential

subscription_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CREDENTIAL = DefaultAzureCredential(exclude_shared_token_cache_credential=True, exclude_environment_credential=True, exclude_managed_identity_credential=True, exclude_visual_studio_code_credential=True)

compute_client = ComputeManagementClient(CREDENTIAL, subscription_id)

def list_vms_in_subscription():
    group_list = compute_client.resource_groups.list()
    for group in group_list:
        list_vms_in_group(group.name)

def list_vms_in_group(group_name):
    for vm in compute_client.virtual_machines.list(group_name):
        print(vm.name)

if __name__ == '__main__':
    list_vms_in_subscription()
2
Mureinik On

The list_vms_in_groups function ignores the group name and instead lists all the VMs:

def list_vms_in_groups(group_name):
    for resource in compute_client.virtual_machines.list(group_name):
        # Here ------------------------------------------^
        if resource.type == "Microsoft.Compute/virtualMachines":
            print(resource.name)
1
Robert Long On

resource_skus.list method returns the SKUs available (for your subscription), not the resource groups or the VMs themselves. list_vms_in_subscription: should iterate over groups in resource_client.resource_groups.list and then call list_vms_in_group with the group name. list_vms_in_group then iterate the VMs in compute_client.virtual_machines.list. Try something like this:

def list_vms_in_subscription():
    for group in resource_client.resource_groups.list():
        list_vms_in_group(group.name)

def list_vms_in_group(group_name):
    for vm in compute_client.virtual_machines.list(group_name):
        print(vm.name)