Skip to content

Instantly share code, notes, and snippets.

@Esl1h
Created April 25, 2023 17:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Esl1h/ebab9460f9f8f1a127708ffc79ece7a4 to your computer and use it in GitHub Desktop.
Save Esl1h/ebab9460f9f8f1a127708ffc79ece7a4 to your computer and use it in GitHub Desktop.
Search AWS over load balancers and target groups to find Load balancers without Target groups and find TGs without Registered targets
#!/bin/bash
AWS_REGION="xx-xxxx-1"
AWS_OUTPUT="json"
AWS_PROFILE="xxx"
# 01- ELBs without Target Groups
load_balancers=$(aws elbv2 describe-load-balancers --query "LoadBalancers[*].LoadBalancerArn" --output text --profile $AWS_PROFILE)
for lb in $load_balancers; do
#printf "$lb"'%b\n'
target_groups=$(aws elbv2 describe-target-groups --load-balancer-arn "$lb" --query "TargetGroups[*].TargetGroupArn" --output text --profile $AWS_PROFILE)
if [ -z "$target_groups" ]; then
lb_name=$(aws elbv2 describe-load-balancers --load-balancer-arn "$lb" --query "LoadBalancers[*].LoadBalancerName" --output text --profile $AWS_PROFILE)
echo "Load balancer $lb_name does not have any target groups."
fi
done
# 02- Only Target Groups without Registered Targets (may or may not have an associated load balancer):
target_groups=$(aws elbv2 describe-target-groups --query "TargetGroups[*].TargetGroupArn" --output text --profile $AWS_PROFILE)
for target_group in $target_groups; do
registered_targets=$(aws elbv2 describe-target-health --target-group-arn $target_group --query "TargetHealthDescriptions[*].Target.Id" --output text --profile $AWS_PROFILE)
if [ -z "$registered_targets" ]; then
echo "Target group without registered targets: $target_group"
fi
done
# 03 - Load balancers that his target groups do not have registered targets
LB_LIST=$(aws elbv2 describe-load-balancers --region $AWS_REGION --output $AWS_OUTPUT --profile $AWS_PROFILE)
for LB in $(echo "${LB_LIST}" | jq -r '.LoadBalancers[].LoadBalancerArn')
do
TG_LIST=$(aws elbv2 describe-target-groups --load-balancer-arn $LB --region $AWS_REGION --output $AWS_OUTPUT --profile $AWS_PROFILE)
for TG in $(echo "${TG_LIST}" | jq -r '.TargetGroups[].TargetGroupArn')
do
TARGET_LIST=$(aws elbv2 describe-target-health --target-group-arn $TG --region $AWS_REGION --output $AWS_OUTPUT --profile $AWS_PROFILE)
if [ "$(echo "${TARGET_LIST}" | jq -r '.TargetHealthDescriptions | length')" == "0" ]
then
echo "Load balancer with ARN $LB has a target group with ARN $TG that has no registered targets."
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment