agent: |
PKlOY0t1kOyexNZAWQTkFilter Out Idle Azure VM Instances
Filter Out Idle Azure VM Instances
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This task identifies virtual machines in Azure that exhibit low or no activity. It typically involves analyzing VM usage metrics over a set period. VMs that demonstrate consistently low activity are marked as idle. This identification is crucial for resource optimization and cost management within Azure environments.
inputs
outputs
from azure.identity import DefaultAzureCredential
from azure.mgmt.monitor import MonitorManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.core.exceptions import HttpResponseError
from datetime import datetime, timedelta
import pytz
# Initialize Azure credentials
credential = DefaultAzureCredential()
try:
# Initialize clients
subscription_id = "955ecf93-74f8-4728-bd2a-31094aa55629"
compute_client = ComputeManagementClient(credential, subscription_id)
monitor_client = MonitorManagementClient(credential, subscription_id)
# Define parameters for idle VM detection
#LOW_CPU_UTILIZATION = 10
#LOOKBACK_PERIOD_DAYS = 7
evaluation_period = timedelta(days=int(LOOKBACK_PERIOD_DAYS)) # Time window for CPU usage evaluation
current_time = datetime.now().replace(tzinfo=pytz.utc)
start_time = current_time - evaluation_period
# Format timespan in ISO 8601 format without microseconds
formatted_start_time = start_time.strftime('%Y-%m-%dT%H:%M:%SZ')
formatted_current_time = current_time.strftime('%Y-%m-%dT%H:%M:%SZ')
# Retrieve all VMs in the subscription
vms = list(compute_client.virtual_machines.list_all())
if vms:
idle_vms = []
for vm in vms:
resource_uri = vm.id
try:
metrics_data = monitor_client.metrics.list(
resource_uri=resource_uri,
timespan=f"{formatted_start_time}/{formatted_current_time}",
interval='PT1H',
metricnames='Percentage CPU',
aggregation='Average'
)
except HttpResponseError as e:
print(f"An error occurred while fetching metrics for VM {vm.name}: {e}")
continue
vm_is_idle = all(data.average <= int(LOW_CPU_UTILIZATION) for item in metrics_data.value for timeseries in item.timeseries for data in timeseries.data if data.average is not None)
if vm_is_idle:
idle_vms.append(vm)
if idle_vms:
print("Idle VMs (Based on CPU Utilization):")
for idle_vm in idle_vms:
# Extracting resource group name from the VM's ID
resource_group_name = idle_vm.id.split('/')[4]
print(f"VM Name: {idle_vm.name}")
print(f"Resource Group: {resource_group_name}")
print(f"Location: {idle_vm.location}")
print(f"Time Created: {idle_vm.time_created}")
print("-" * 30)
else:
print("No idle VMs found based on CPU utilization criteria.")
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