Manage AWS EC2 ASGs with 0 Desired and Min count
This runbook involves identifying inactive ASGs that may not be serving any operational purpose. The remediation step, often involves deletion, helps optimize resource usage and reduce unnecessary costs. It's essential for maintaining a streamlined and cost-effective cloud infrastructure.
- 1gI9PbPfVbKy0jWV6Kt3QList All AWS EC2 Auto Scaling Groups (ASGs)
1
List All AWS EC2 Auto Scaling Groups (ASGs)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task involves retrieving information about all the ASGs within a specified AWS region or across multiple regions. It helps in monitoring and managing the scaling behaviors of instances automatically, ensuring that the number of instances adjusts according to the set criteria, such as changes in demand or defined schedules.
inputsoutputsimport boto3 from botocore.exceptions import NoCredentialsError, PartialCredentialsError, BotoCoreError, ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] def list_all_regions(): ec2 = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1') return [region['RegionName'] for region in ec2.describe_regions()['Regions']] def list_auto_scaling_groups(region=None): regions = [region] if region else list_all_regions() asg_details = [] for region in regions: try: asg_client = boto3.client('autoscaling', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name=region) except (NoCredentialsError, PartialCredentialsError, BotoCoreError, ClientError) as e: print(f"Failed for {region}: {e}") continue paginator = asg_client.get_paginator('describe_auto_scaling_groups') try: for page in paginator.paginate(): for asg in page['AutoScalingGroups']: asg['CreatedTime'] = asg['CreatedTime'].strftime('%Y-%m-%d %H:%M:%S') if 'CreatedTime' in asg else 'N/A' asg['Region'] = region # Ensuring the region is part of the details asg_details.append(asg) except ClientError as e: print(f"Failed for {region}: {e}") return asg_details def display_asg_details(data): if not data: print("No Auto Scaling Groups found.") return table = context.newtable() table.title = "Auto Scaling Group Details" table.num_cols = 6 # Add an additional column for 'CreatedTime' table.num_rows = len(data) + 1 # Rows for headers plus each ASG table.has_header_row = True # Define header names with the addition of 'CreatedTime' headers = ["AutoScalingGroupName", "Region", "MinSize", "MaxSize", "DesiredCapacity", "CreatedTime"] # Set headers in the first row for col_num, header in enumerate(headers): table.setval(0, col_num, header) # Assume setval sets value at (row, col) # Populate the table with ASG data for row_num, asg in enumerate(data, start=1): # Starting from the second row values = [ asg["AutoScalingGroupName"], asg["Region"], str(asg["MinSize"]), str(asg["MaxSize"]), str(asg["DesiredCapacity"]), asg["CreatedTime"] # Ensure CreatedTime is included and properly formatted ] for col_num, value in enumerate(values): table.setval(row_num, col_num, value) #region_name = None # Set to None to list ASGs for all available regions or specify a region asg_list = list_auto_scaling_groups(region_name) if asg_list: display_asg_details(asg_list) #print("\nComplete ASG List:") #print(asg_list) # Display the complete list of ASG objects for downstream tasks else: print("No Auto Scaling Groups found.")copied1 - 2IbXhdciWjypv8Y0MQZa3Filter ASGs: Identify ASGs where both the desired capacity and minimum size are zero.
2
Filter ASGs: Identify ASGs where both the desired capacity and minimum size are zero.
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task filters ASGs to identify those with both desired capacity and minimum size set to zero involves checking Auto Scaling Groups to find inactive configurations. This process helps in identifying ASGs that are not currently scaling any instances, potentially leading to cleanup actions to optimize resource usage and reduce costs in AWS environments.
inputsoutputsimport boto3 from botocore.exceptions import NoCredentialsError, PartialCredentialsError, BotoCoreError, ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] def filter_asgs(asg_list): """ Filter ASGs where both the desired capacity and minimum size are zero. """ filtered_asgs = [asg for asg in asg_list if asg['MinSize'] == 0 and asg['DesiredCapacity'] == 0] return filtered_asgs def display_asg_details(data): """ Display the details of filtered ASGs in a formatted table. """ # Initialize table with the desired structure and headers table = context.newtable() table.title = "Filtered Auto Scaling Groups" table.num_cols = 5 # Number of columns according to headers table.num_rows = 1 # Starts with one row for headers table.has_header_row = True # Define header names based on the new structure headers = ["AutoScalingGroupName", "Region", "MinSize", "MaxSize", "DesiredCapacity"] # Set headers in the first row for col_num, header in enumerate(headers): table.setval(0, col_num, header) # Populate the table with ASG data for row_num, asg in enumerate(data, start=1): # Starting from the second row table.num_rows += 1 # Add a row for each ASG values = [ asg["AutoScalingGroupName"], asg["Region"], str(asg["MinSize"]), str(asg["MaxSize"]), str(asg["DesiredCapacity"]) ] for col_num, value in enumerate(values): table.setval(row_num, col_num, value) # Assuming asg_list is passed from an upstream task filtered_asgs = filter_asgs(asg_list) if filtered_asgs: display_asg_details(filtered_asgs) else: print("No Auto Scaling Groups found with MinSize and DesiredCapacity set to zero.") context.skip_sub_tasks = Truecopied2- 2.1HBJ0gDH9Wt26YazBFB5PDelete AWS EC2 Auto Scaling Groups (ASGs)
2.1
Delete AWS EC2 Auto Scaling Groups (ASGs)
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.This task involves removing specified ASGs from the AWS environment. This operation is critical for cleaning up unused or unnecessary resources, managing costs, or decommissioning services.
inputsoutputsimport boto3 from botocore.exceptions import ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] def delete_auto_scaling_groups(filtered_asgs): """ Deletes a list of auto scaling groups provided in filtered_asgs. Each ASG dict must contain 'AutoScalingGroupName' and 'Region'. """ for asg in filtered_asgs: region = asg['Region'] asg_name = asg['AutoScalingGroupName'] try: # Initialize the boto3 client for AutoScaling in the specified region client = boto3.client('autoscaling', aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=region) # Delete the Auto Scaling group client.delete_auto_scaling_group(AutoScalingGroupName=asg_name, ForceDelete=True) print(f"Successfully requested deletion of ASG: {asg_name} in {region}") except ClientError as e: print(f"Failed to delete ASG: {asg_name} in {region}. Error: {e}") # Example filtered_asgs list #filtered_asgs = [{"AutoScalingGroupName":"test1-asg","AutoScalingGroupARN":"arn:aws:autoscaling:us-east-1:188379622596:autoScalingGroup:4f564e69-b9f3-4d3f-8cfc-5ee7468f1396:autoScalingGroupName/test1-asg","MixedInstancesPolicy":{"LaunchTemplate":{"LaunchTemplateSpecification":{"LaunchTemplateId":"lt-0b4e1233a5006c59b","LaunchTemplateName":"test1-asg-template","Version":"$Default"},"Overrides":[{"InstanceType":"t3.micro"},{"InstanceType":"t3a.micro"}]},"InstancesDistribution":{"OnDemandAllocationStrategy":"prioritized","OnDemandBaseCapacity":0,"OnDemandPercentageAboveBaseCapacity":0,"SpotAllocationStrategy":"price-capacity-optimized"}},"MinSize":0,"MaxSize":0,"DesiredCapacity":0,"DefaultCooldown":300,"AvailabilityZones":["us-east-1a","us-east-1b","us-east-1c"],"LoadBalancerNames":[],"TargetGroupARNs":[],"HealthCheckType":"EC2","HealthCheckGracePeriod":300,"Instances":[],"CreatedTime":"2024-05-27 10:49:04","SuspendedProcesses":[],"VPCZoneIdentifier":"subnet-b8482599,subnet-26325179,subnet-836e58ce","EnabledMetrics":[],"Tags":[],"TerminationPolicies":["Default"],"NewInstancesProtectedFromScaleIn":false,"ServiceLinkedRoleARN":"arn:aws:iam::188379622596:role/aws-service-role/autoscaling.amazonaws.com/AWSServiceRoleForAutoScaling","CapacityRebalance":true,"TrafficSources":[],"Region":"us-east-1"}] # Deleting ASGs delete_auto_scaling_groups(filtered_asgs)copied2.1