I have a Python script that lists all VMs in a specific Azure resource
group. The script collects and prints details such as VM name,
location, size, and OS type.
Here is the current script:
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.resource import ResourceManagementClient
subscription_id = 'xxxxxxxxxx'
resource_group_name = 'yyyyyyyyyy'
credential = DefaultAzureCredential()
compute_client = ComputeManagementClient(credential, subscription_id)
resource_client = ResourceManagementClient(credential, subscription_id)
vm_list = compute_client.virtual_machines.list(resource_group_name)
vm_details_list = []
for vm in vm_list:
vm_details = {
'name': vm.name,
'location': vm.location,
'vm_size': vm.hardware_profile.vm_size,
'os_type': vm.storage_profile.os_disk.os_type
}
vm_details_list.append(vm_details)
for vm in vm_details_list:
print(f"VM Name: {vm['name']}")
print(f"Location: {vm['location']}")
print(f"VM Size: {vm['vm_size']}")
print(f"OS Type: {vm['os_type']}")
print('---')
I need to modify this script to only list VMs whose state is
‘running’. How can I achieve this? Thank you for your help!
New contributor
user15042420 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.