Sign in

ELB Health Monitoring

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

    Get unhealthy resources attached to AWS ELBs(Elastic Load Balancers)

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

    This runbook retrieves the list of resources, such as instances or targets, that are marked as 'unhealthy' or 'OutOfService', and are associated with AWS Elastic Load Balancers (ELB). This helps in identifying potential issues and ensuring the smooth operation and high availability of applications.

    1
    1. 1.1

      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.

      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
      1.1
    2. 1.2

      Get Unhealthy targets associated to an ALB or NLB

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

      This task retrieves and lists targets that are marked as 'unhealthy' and linked to AWS Application Load Balancers (ALB) or Network Load Balancers (NLB). This process helps in detecting non-performing targets to maintain optimal load distribution and service availability.

      import boto3 from botocore.exceptions import ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] def get_unhealthy_targets(regions, elb_arn=None): """ Fetch targets (instances) that are in "unhealthy" state for AWS Application Load Balancers (ALBs) and Network Load Balancers (NLBs). Parameters: - elb_arn (str, optional): Specific ARN 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 targets. """ # Initialize an empty list to store results result = [] # Loop through each specified region to check for unhealthy targets for reg in regions: try: # Create a new client for the ELBv2 service in the specified region elbv2_client = boto3.client('elbv2', aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=reg) # Retrieve the list of all ALBs and NLBs in the current region elbs = elbv2_client.describe_load_balancers()["LoadBalancers"] # Loop through each Load Balancer and inspect its targets for elb in elbs: # If a specific ELB ARN is provided, skip all other load balancers if elb_arn and elb["LoadBalancerArn"] != elb_arn: continue # Get all target groups associated with the current load balancer target_groups = elbv2_client.describe_target_groups(LoadBalancerArn=elb["LoadBalancerArn"])["TargetGroups"] # Check the health status of each target within the target group for tg in target_groups: health_descriptions = elbv2_client.describe_target_health(TargetGroupArn=tg["TargetGroupArn"])["TargetHealthDescriptions"] # If a target is found to be "unhealthy", store its details in the result list for desc in health_descriptions: if desc["TargetHealth"]["State"] == "unhealthy": data_dict = { "target_id": desc["Target"]["Id"], "region": reg, "load_balancer_arn": elb["LoadBalancerArn"], "target_group_arn": tg["TargetGroupArn"] } result.append(data_dict) # Catch any AWS-related exceptions and print an error message except ClientError as e: print(f"ClientError in region {reg}: {e}") # Catch any other general exceptions and print an error message except Exception as e: print(f"An error occurred in region {reg}: {e}") return result # Specify the AWS regions to check for unhealthy targets #regions_to_check = ['us-east-1', 'us-west-2'] # Retrieve and print the details of any found unhealthy targets unhealthy_targets = get_unhealthy_targets(regions) if unhealthy_targets: print("Unhealthy targets detected:") for target in unhealthy_targets: print(f"Region: {target['region']}\nLoadBalancer ARN: {target['load_balancer_arn']}\nTargetGroup ARN: {target['target_group_arn']}\nTarget ID: {target['target_id']}\n") else: print("No unhealthy targets found.")
      copied
      1.2
  2. 2

    Enforce HTTPS Redirection across AWS ALB

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

    Enforcing HTTPS redirection on AWS ALB ensures all HTTP traffic is redirected to HTTPS, enhancing data security. This is achieved by modifying the ALB's listener rules, ensuring encrypted and secure data transit.

    2
    1. 2.1

      List all AWS ALB Listeners without HTTPS Redirection

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

      This task identifies and lists AWS ALB listeners that are not configured to redirect HTTP traffic to HTTPS, potentially exposing unencrypted data in transit.

      import boto3 from botocore.exceptions import ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] # target_region = 'us-east-1' # Set this to your desired region or None for all regions # Initialize the EC2 client to get a list of all regions ec2_client = boto3.client('ec2',aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name='us-east-1') # If target_region is not defined or None, fetch all regions, otherwise use the provided region regions = [region['RegionName'] for region in ec2_client.describe_regions()['Regions']] if not locals().get('target_region') else [target_region] # Iterate through the selected regions to check ALB listeners for region in regions: elbv2_client = boto3.client('elbv2',aws_access_key_id=access_key,aws_secret_access_key=secret_key, region_name=region) listeners_without_redirect = [] total_listeners = 0 # Counter to keep track of total listeners print(f"\nChecking ALB listeners in region {region}...") try: alb_response = elbv2_client.describe_load_balancers() except ClientError as e: print(f"Error fetching ALB list in region {region}: {e}") continue # Skip to the next region if there's an error fetching ALBs for this one for lb in alb_response.get('LoadBalancers', []): try: listener_response = elbv2_client.describe_listeners(LoadBalancerArn=lb['LoadBalancerArn']) total_listeners += len(listener_response['Listeners']) except ClientError as e: print(f"Error fetching listeners for ALB {lb['LoadBalancerName']} in region {region}: {e}") continue # Skip to the next ALB if there's an error fetching listeners for this one for listener in listener_response['Listeners']: if listener['Protocol'] == 'HTTP': redirect_actions = [action for action in listener['DefaultActions'] if action['Type'] == 'redirect'] if not redirect_actions: listeners_without_redirect.append({ 'Region': region, 'ALBName': lb['LoadBalancerName'], 'ListenerArn': listener['ListenerArn'] }) # Summary for the region if total_listeners == 0: print(f"No listeners found in region {region}.") elif listeners_without_redirect: print(listeners_without_redirect) print(f"In region {region}, found {len(listeners_without_redirect)} listener(s) without HTTPS redirection:") for listener_info in listeners_without_redirect: print(f"Region: {listener_info['Region']}, ALB: {listener_info['ALBName']}, Listener ARN: {listener_info['ListenerArn']}") else: print(f"All listeners in region {region} have HTTPS redirection configured.") context.skip_sub_tasks=True
      copied
      2.1
    2. 2.2

      Modify AWS ALB Listeners to Enforce HTTPS Redirection

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

      This procedure adjusts AWS ALB listeners to ensure that all HTTP traffic is automatically redirected to HTTPS, enhancing the security of data transmission by using encryption.

      import boto3 from botocore.exceptions import ClientError creds = _get_creds(cred_label)['creds'] access_key = creds['username'] secret_key = creds['password'] ''' # Example structure, list passed down from upstream task listeners_without_redirect = [ {'Region': 'us-east-1', 'ALBName': 'alb-blahblah', 'ListenerArn': 'arn:aws:elasticloadbalancing:us-east-1:355237452254:listener/app/alb-blahblah/599c713a19a4afce/56d57ff44837d30f'}, {'Region': 'us-east-1', 'ALBName': 'alb-blahblah', 'ListenerArn': 'arn:aws:elasticloadbalancing:us-east-1:355237452254:listener/app/alb-blahblah/599c713a19a4afce/6a54c2e7d3c08fee'} ] ''' # Check if there are any listeners to process if not listeners_without_redirect: print("No listeners provided to modify. Exiting task.") else: print(f"Attempting to modify {len(listeners_without_redirect)} listener(s) to enforce HTTP redirection...") for listener_info in listeners_without_redirect: region = listener_info['Region'] listener_arn = listener_info['ListenerArn'] elbv2_client = boto3.client('elbv2', aws_access_key_id=access_key,aws_secret_access_key=secret_key,region_name=region) try: elbv2_client.modify_listener( ListenerArn=listener_arn, DefaultActions=[ { 'Type': 'redirect', 'Order': 1, 'RedirectConfig': { 'Protocol': 'HTTPS', 'Port': '443', 'Host': '#{host}', 'Path': '/#{path}', 'Query': '#{query}', 'StatusCode': 'HTTP_301' } } ] ) print(f"Modified listener {listener_arn} in ALB {listener_info['ALBName']} to enforce HTTP redirection.") except ClientError as e: print(f"Error modifying listener {listener_arn} in ALB {listener_info['ALBName']} in region {region}: {e}") print("Modification task completed.")
      copied
      2.2