Sign in
agent:

List All Azure VM Instances

There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

This task displays information about all virtual machines within a specific azure subscription and provides essential details such as VM names, their resource groups, locations, and creation times. It's a vital process for cloud administrators to manage and monitor their VM infrastructure effectively, enabling informed decisions about resource utilization and infrastructure management.

from azure.identity import DefaultAzureCredential from azure.mgmt.compute import ComputeManagementClient from azure.core.exceptions import HttpResponseError # Initialize Azure credentials credential = DefaultAzureCredential() try: compute_client = ComputeManagementClient(credential, subscription_id) # Set location filter (set to None for all regions, or to a specific region like 'eastus') #location = None # Example: 'eastus' # Try to retrieve all VMs in the subscription try: vms = list(compute_client.virtual_machines.list_all()) except HttpResponseError as e: print(f"An error occurred while listing VMs: {e}") vms = [] # Continue only if VMs are found if vms: # Filter VMs by location if location is set if location: vms = [vm for vm in vms if vm.location.lower() == location.lower()] print(f"{len(vms)} VM instances found in the subscription.") for vm in vms: # Extracting resource group name from the VM's ID resource_group_name = vm.id.split('/')[4] # Printing VM details print(f"VM Name: {vm.name}") print(f"Resource Group: {resource_group_name}") print(f"Location: {vm.location}") print(f"Time Created: {vm.time_created}") #print(vm.as_dict()) # for debugging print("-" * 30) else: print("No VM instances found in the subscription.") except HttpResponseError as e: print(f"An error occurred with the Azure HTTP response: {e}") except Exception as e: print(f"An unexpected error occurred: {e}")
copied