agent: |
RKCYZEpNmGgj6MW1811qGet Unhealthy instances attached to Classic Load Balancers
Get Unhealthy instances attached to Classic Load Balancers
There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.
This task checks for instances which are OutOfService and are associated with a Classic Load Balancer.
inputs
outputs
import boto3
from botocore.exceptions import ClientError
creds = _get_creds(cred_label)['creds']
access_key = creds['username']
secret_key = creds['password']
def get_unhealthy_instances(regions,elb_name=None):
"""
Fetch instances that are in "OutOfService" state for AWS Elastic Load Balancers (ELBs).
Parameters:
- elb_name (str, optional): Specific name of the Elastic Load Balancer to check. Default is None, which checks all ELBs.
- regions (list): List of AWS regions to check.
Returns:
- list: A list of dictionaries containing details of unhealthy instances.
"""
result = []
# Loop through each specified region to check the health of instances under ELBs
for reg in regions:
try:
# Initialize ELB client for the specified region
elb_client = boto3.client('elb', aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=reg)
# Get a list of all load balancers in the current region
elbs = elb_client.describe_load_balancers()["LoadBalancerDescriptions"]
# Loop through each ELB to check the health of its instances
for elb in elbs:
# If a specific elb_name is provided, then skip the ELBs that don't match the name
if elb_name and elb["LoadBalancerName"] != elb_name:
continue
# Fetch the health status of instances attached to the current ELB
res = elb_client.describe_instance_health(LoadBalancerName=elb["LoadBalancerName"])
# Check each instance's health status
for instance in res['InstanceStates']:
# If the instance is "OutOfService", add its details to the result list
if instance['State'] == "OutOfService":
data_dict = {
"instance_id": instance["InstanceId"],
"region": reg,
"load_balancer_name": elb["LoadBalancerName"]
}
result.append(data_dict)
# Handle specific ClientError exceptions (e.g. permission issues, request limits)
except ClientError as e:
print(f"ClientError in region {reg}: {e}")
# Handle general exceptions
except Exception as e:
print(f"An error occurred in region {reg}: {e}")
return result
# Specify the AWS regions to check for unhealthy instances
#regions_to_check = ['us-east-1', 'us-west-2']
# Fetch the list of unhealthy instances
unhealthy_instances = get_unhealthy_instances(regions)
# Print the details of unhealthy instances, if any
if unhealthy_instances:
print("Unhealthy instances detected:")
for instance in unhealthy_instances:
print(f"Region: {instance['region']}, LoadBalancer: {instance['load_balancer_name']}, InstanceID: {instance['instance_id']}")
else:
print("No unhealthy instances found.")
copied