Get Unused AWS Load Balancer and Target health status


#!/bin/bash
RED='\033[0;31m'
NC='\033[0m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[33m'
LZ_ENVIRONMENT="$1"
REGION="$2"
TIMESTAMP=$(date "+%F %T")

#Get Authorisation
echo -e "${BLUE}Authorising...${NC}"
# Function to get all load balancer ARNs
get_load_balancer_arns() {
     aws elbv2 describe-load-balancers --region "$REGION" --query 'LoadBalancers[*].LoadBalancerArn' --output json | jq -r '.[]'
}

# Function to get target group ARNs for a load balancer
get_target_group_arns() {
    local lb_arn="$1"
     aws elbv2 describe-target-groups --region "$REGION" --load-balancer-arn "$lb_arn" --query 'TargetGroups[*].TargetGroupArn' --output json | jq -r '.[]'
}

# Function to check target health for a load balancer
check_load_balancer_health() {
    local lb_arn="$1"
    local target_group_arns=($(get_target_group_arns "$lb_arn"))
    
    local has_targets=false
    local has_unhealthy_targets=false

    for target_group_arn in "${target_group_arns[@]}"; do
        local lb_arn_for_group=$(get_load_balancer_arns "$target_group_arn")
        local target_health=$($Auth aws elbv2 describe-target-health --region "$REGION" --target-group-arn "$target_group_arn" --query 'TargetHealthDescriptions[*].Target.Id' --output json)
        
        if [ "$target_health" != "[]" ]; then
            has_targets=true

            local is_unhealthy=$($Auth aws elbv2 describe-target-health --region "$REGION" --target-group-arn "$target_group_arn" --query 'TargetHealthDescriptions[?TargetHealth.State==`unhealthy`]' --output json)
            
            if [ "$is_unhealthy" != "[]" ]; then
                has_unhealthy_targets=true
                break
            fi
        fi
    done

    if [ "$has_unhealthy_targets" == "true" ]; then
        echo "Used,Unhealthy,$lb_arn"
    elif [ "$has_targets" == "false" ]; then
        echo "Unused,N/A,$lb_arn"
    else
        echo "Used,Healthy,$lb_arn"
    fi
}

# Generate CSV report
generate_csv_report() {
    echo "LoadBalancerType,TargetHealthStatus,LoadBalancerArn" > "$csv_output_file"
    local load_balancer_arns=($(get_load_balancer_arns))
    
    for lb_arn in "${load_balancer_arns[@]}"; do
        check_load_balancer_health "$lb_arn" >> "$csv_output_file"
    done
}

# Set output file paths
csv_output_file="${LZ_ENVIRONMENT}_${REGION}_${TIMESTAMP}_load_balancer_report.csv"

# Generate CSV report
generate_csv_report

echo -e "${BLUE} Generating CSV Report...${NC}"

Comments

Popular posts from this blog

AWS CLI Get Security Group ID with Name.[ wild card support] Bash Script

AWS CLI Get Security Group ID with Name. Python Boto3 [ wild card support] Python Boto3

AMI Age Calculator of Running AWS EC2 Instances and Generate CSV Report