Created
October 12, 2023 09:12
-
-
Save readybuilderone/b781818aaeb9345a7c6316801a539b46 to your computer and use it in GitHub Desktop.
find alb target group for given ec2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 检查是否提供了实例ID和区域作为参数 | |
if [ -z "$1" ] || [ -z "$2" ]; then | |
echo "Usage: $0 <Instance ID> <AWS Region>" | |
exit 1 | |
fi | |
# 从命令行参数获取实例ID和AWS区域 | |
INSTANCE_ID="$1" | |
AWS_REGION="$2" | |
# 查询实例是否存在 | |
instance_info=$(aws ec2 describe-instances --region $AWS_REGION --instance-ids $INSTANCE_ID) | |
# 检查实例是否存在 | |
if [ -z "$instance_info" ]; then | |
echo "EC2 instance with ID '$INSTANCE_ID' not found in region $AWS_REGION." | |
exit 1 | |
fi | |
# 提取实例所属的VPC ID | |
vpc_id=$(echo "$instance_info" | jq -r '.Reservations[0].Instances[0].VpcId') | |
# 查询实例所属VPC中的所有目标组ARN | |
target_group_arns=$(aws elbv2 describe-target-groups --region $AWS_REGION --query "TargetGroups[?VpcId=='$vpc_id'].TargetGroupArn" --output text) | |
# 存储匹配的目标组 | |
matching_target_groups=() | |
# 检查实例是否已注册到某个目标组 | |
for target_group_arn in $target_group_arns; do | |
targets=$(aws elbv2 describe-target-health --region $AWS_REGION --target-group-arn $target_group_arn --targets "Id=$INSTANCE_ID" --query "TargetHealthDescriptions" --output text) | |
if [ -n "$targets" ]; then | |
matching_target_groups+=($target_group_arn) | |
fi | |
done | |
# 输出匹配的目标组 | |
if [ ${#matching_target_groups[@]} -gt 0 ]; then | |
echo "Target Groups for EC2 instance ID '$INSTANCE_ID' in region '$AWS_REGION':" | |
for target_group_arn in "${matching_target_groups[@]}"; do | |
echo "$target_group_arn" | |
done | |
else | |
echo "EC2 instance ID '$INSTANCE_ID' is not registered in any Target Groups in VPC '$vpc_id' in region '$AWS_REGION'." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
./find_ec2_target_group.sh