如何使用boto3及AWS CLI获取EC2实例与负载均衡器详情并解析输出
Got it, let's break this down step by step for both Boto3 and AWS CLI—two common ways to grab that EC2 and Load Balancer info you need.
Boto3 is perfect if you want to automate this into scripts or integrate with other Python tools. Here's how to pull the details you're after:
1. Fetch EC2 Instance Details
This script will grab core instance info like ID, IP addresses, and configuration settings:
import boto3 # Initialize the EC2 client ec2_client = boto3.client('ec2') # Fetch all EC2 instances (add filters if you need specific ones) response = ec2_client.describe_instances() # Parse and print relevant details for reservation in response['Reservations']: for instance in reservation['Instances']: print(f"Instance ID: {instance['InstanceId']}") print(f"Private IP: {instance['PrivateIpAddress']}") # Handle instances without a public IP (like private subnets) print(f"Public IP: {instance.get('PublicIpAddress', 'N/A')}") print(f"Instance Type: {instance['InstanceType']}") print(f"VPC ID: {instance['VpcId']}") print(f"Current State: {instance['State']['Name']}") print("---")
2. Fetch Load Balancer (ELBv2) Details
For Application/Network Load Balancers (most common modern LBs), use the elbv2 client:
# Initialize the ELBv2 client elb_client = boto3.client('elbv2') # Fetch all Load Balancers lb_response = elb_client.describe_load_balancers() # Parse and print LB info for lb in lb_response['LoadBalancers']: print(f"Load Balancer Name: {lb['LoadBalancerName']}") print(f"LB DNS Name: {lb['DNSName']}") print(f"LB ARN: {lb['LoadBalancerArn']}") print(f"VPC ID: {lb['VpcId']}") print(f"Scheme: {lb['Scheme']}") # internet-facing or internal print("---")
3. Link Instances to Their Load Balancers
To connect instances to the LBs they're attached to, you need to check Target Groups (LBs route traffic through these):
# Get all Target Groups and their associated LBs tg_response = elb_client.describe_target_groups() for tg in tg_response['TargetGroups']: tg_arn = tg['TargetGroupArn'] lb_arns = tg['LoadBalancerArns'] if not lb_arns: continue # Skip TGs not linked to any LB # Get instances registered to this Target Group health_response = elb_client.describe_target_health(TargetGroupArn=tg_arn) for target_health in health_response['TargetHealthDescriptions']: instance_id = target_health['Target']['Id'] # Match instance ID to details from earlier EC2 response instance = next(i for r in response['Reservations'] for i in r['Instances'] if i['InstanceId'] == instance_id) print(f"Instance {instance_id} (Private IP: {instance['PrivateIpAddress']}) is linked to:") for lb_arn in lb_arns: lb = next(l for l in lb_response['LoadBalancers'] if l['LoadBalancerArn'] == lb_arn) print(f" - Load Balancer: {lb['LoadBalancerName']}") print("---")
The CLI is great for quick ad-hoc queries. We'll use --query (JMESPath syntax) to filter output and avoid sifting through raw JSON.
1. Fetch EC2 Instance Details (Filtered)
This command pulls exactly the fields you mentioned, formatted as a readable table:
aws ec2 describe-instances \ --query 'Reservations[*].Instances[*].{ID: InstanceId, PrivateIP: PrivateIpAddress, PublicIP: PublicIpAddress, Type: InstanceType, VPC: VpcId, State: State.Name}' \ --output table
--query: Uses JMESPath to extract and rename fields for clarity.--output table: Makes the output easy to read (swap tojsonif you need machine-readable data).
2. Fetch Load Balancer Details (Filtered)
For ELBv2 (Application/Network LBs), use this command:
aws elbv2 describe-load-balancers \ --query 'LoadBalancers[*].{Name: LoadBalancerName, DNS: DNSName, ARN: LoadBalancerArn, VPC: VpcId, Scheme: Scheme}' \ --output table
3. Link Instances to Load Balancers
To connect instances to their LBs, we'll combine Target Group queries with jq (a lightweight JSON parser—install it first if you don't have it):
# Loop through Target Groups, get registered instances, and link to LBs aws elbv2 describe-target-groups \ --query 'TargetGroups[*].{TGName: TargetGroupName, LBArns: LoadBalancerArns, TGArn: TargetGroupArn}' \ --output json | jq '.[]' | while read -r tg; do tg_arn=$(echo "$tg" | jq -r '.TGArn') lb_arns=$(echo "$tg" | jq -r '.LBArns[]') tg_name=$(echo "$tg" | jq -r '.TGName') # Get instances in this Target Group aws elbv2 describe-target-health --target-group-arn "$tg_arn" \ --query 'TargetHealthDescriptions[*].Target.Id' \ --output text | tr '\t' '\n' | while read -r instance_id; do # Get instance private IP instance_ip=$(aws ec2 describe-instances --instance-ids "$instance_id" --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text) # Get LB name from ARN for lb_arn in $lb_arns; do lb_name=$(aws elbv2 describe-load-balancers --load-balancer-arns "$lb_arn" --query 'LoadBalancers[0].LoadBalancerName' --output text) echo "Instance $instance_id (Private IP: $instance_ip) → Target Group: $tg_name → Load Balancer: $lb_name" done done done
内容的提问来源于stack exchange,提问作者Rockinroll




