#!/bin/bash

# Fetch Target Groups
TARGET_GROUP_ARNS="$(for listener_arn in $(aws elbv2 describe-listeners \
  --load-balancer-arn arn:aws:elasticloadbalancing:eu-west-2:438465125612:loadbalancer/net/nlb-gld/9a421b9496263f79 \
  --query 'Listeners[*].ListenerArn' --output text); do
  aws elbv2 describe-rules --listener-arn "$listener_arn" \
    --query 'Rules[*].Actions[*].TargetGroupArn' --output text
done)"

# Fetch Targets and Their Instance IDs and Ports
for tg_arn in $TARGET_GROUP_ARNS; do
  TARGET_INSTANCES=$(aws elbv2 describe-target-health \
    --target-group-arn "$tg_arn" \
    --query 'TargetHealthDescriptions[*].Target.[Id,Port]' --output text)

  while IFS=$'\n' read -r instance; do
    INSTANCE_ID="$(echo "$instance" | awk '{print $1}')"
    PORT="$(echo "$instance" | awk '{print $2}')"
    IP_ADDRESS="$(aws ec2 describe-instances \
      --instance-ids "$INSTANCE_ID" \
      --query 'Reservations[*].Instances[*].PrivateIpAddress' --output text)"
    echo "Instance ID: $INSTANCE_ID, IP Address: $IP_ADDRESS, Port: $PORT"
  done <<<"$TARGET_INSTANCES"
done
