Sign in
agent:

Delete Underutilized Azure VM Instances

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

This runbook identifies and deletes Azure virtual machines that are not being efficiently utilized. This often involves analyzing usage metrics to determine which VMs are idle or minimally used over a certain period. The goal is to optimize resource allocation and reduce unnecessary costs by decommissioning VMs that are no longer needed or are underperforming, thereby improving overall cloud infrastructure efficiency and cost-effectiveness.

  1. 1

    Get Azure Subscription Id from CLI

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

    This task retrieves the unique identifier for an Azure subscription using the Azure CLI. This ID is essential for managing resources and services tied to a specific Azure subscription programmatically.

    import json try: result = _exe(None, "az account show") account_info = json.loads(result) subscription_id = account_info["id"] print("Fetched Subscription Id") print(subscription_id) # for debugging except json.JSONDecodeError: print("Error decoding JSON response from Azure CLI.") subscription_id = None
    copied
    1
  2. 2

    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
    2
  3. 3

    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.

    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
    3
  4. 4

    Delete Azure VM Instances

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

    This task deletes specified virtual machines from Azure's cloud services. This process frees up associated resources and halts related expenses. It's crucial for optimizing resource usage, but it's irreversible, necessitating careful decision-making.

    from azure.identity import DefaultAzureCredential from azure.mgmt.compute import ComputeManagementClient from azure.core.exceptions import HttpResponseError # Initialize Azure credentials credential = DefaultAzureCredential() # Initialize ComputeManagementClient compute_client = ComputeManagementClient(credential, subscription_id) # vm_name_to_delete = "test-vm-1" # Name of the VM to be deleted # To be initialized in the input parameters try: # Find the VM to delete based on the name vm_to_delete = next((vm for vm in idle_vms if vm.name == vm_name_to_delete), None) if vm_to_delete: # Extracting resource group name from the VM's ID resource_group_name = vm_to_delete.id.split('/')[4] print(f"Initiating deletion of VM: {vm_name_to_delete} in Resource Group: {resource_group_name}") # Begin deletion of the specified VM delete_operation = compute_client.virtual_machines.begin_delete(resource_group_name, vm_name_to_delete) delete_operation.wait() # Wait for the delete operation to complete print(f"VM {vm_name_to_delete} has been successfully deleted.") else: print(f"No VM found with the name '{vm_name_to_delete}' 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
    4