Sign in
agent:

Filter Out Idle AKS Clusters

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

This task involves identifying and listing Azure Kubernetes Service (AKS) clusters that are underutilized or not actively running workloads. By pinpointing these clusters, users can optimize costs and resources by potentially shutting down or deleting them.

import azure.identity from azure.mgmt.monitor import MonitorManagementClient def filter_low_cpu_clusters(clusters, monitor_client, low_cpu_threshold): low_cpu_clusters = [] for cluster in clusters: try: # Fetch CPU utilization metrics for the cluster metrics_data = monitor_client.metrics.list( resource_uri=cluster.id, metricnames='node_cpu_usage_percentage', result_type='Data' ) # Extract non-None average values valid_averages = [time_series.average for time_series in metrics_data.value[0].timeseries[0].data if time_series.average is not None] # Check the average CPU utilization if valid_averages: # Ensure there are valid values before calculating average avg_cpu = sum(valid_averages) / len(valid_averages) if avg_cpu < int(low_cpu_threshold): low_cpu_clusters.append(cluster) except Exception as e: print(f"Failed to fetch metrics for cluster {cluster.name}: {e}") return low_cpu_clusters if subscription_id: # Initialize Azure credentials credential = azure.identity.DefaultAzureCredential() # Setup Azure Monitor client monitor_client = MonitorManagementClient(credential, subscription_id) # Filter clusters with low CPU utilization clusters_filtered = filter_low_cpu_clusters(all_clusters, monitor_client) print(clusters_filtered) # for debugging print(f"Clusters with low CPU utilization:") for cluster in clusters_filtered: print(f" - Name: {cluster.name}, Location: {cluster.location}")
copied