如何通过AWS CLI查找使用指定子网的所有ELB
Got it, I've been in your shoes before when dealing with subnet IP exhaustion—tracking down all resources using a specific subnet can be tricky, especially since ELBs often tie to multiple subnets. The VPC-level query you mentioned works, but here's how to narrow it down directly to your target subnet:
For Classic Load Balancers (ELB Classic)
Classic ELBs store their associated subnets in a Subnets array in the API response. Use the JMESPath contains() function to check if this array includes your target subnet ID:
# Replace subnet-xxxxxx with your actual subnet ID aws elb describe-load-balancers --query 'LoadBalancerDescriptions[?contains(Subnets, `subnet-xxxxxx`)].LoadBalancerName'
If you want more details than just the name (like ARN or DNS), adjust the query output—for example:
aws elb describe-load-balancers --query 'LoadBalancerDescriptions[?contains(Subnets, `subnet-xxxxxx`)].[LoadBalancerName, LoadBalancerARN, DNSName]'
For Application/Network Load Balancers (ALB/NLB)
ALBs and NLBs use the elbv2 API instead of the classic elb API. Their subnet info lives under the AvailabilityZones array, where each entry has a SubnetId field. Use a nested JMESPath check to target this:
# Replace subnet-xxxxxx with your actual subnet ID aws elbv2 describe-load-balancers --query 'LoadBalancers[?contains(AvailabilityZones[].SubnetId, `subnet-xxxxxx`)].LoadBalancerName'
Again, modify the output fields if you need more context:
aws elbv2 describe-load-balancers --query 'LoadBalancers[?contains(AvailabilityZones[].SubnetId, `subnet-xxxxxx`)].{Name: LoadBalancerName, ARN: LoadBalancerArn, DNS: DNSName}'
Quick Tip
If you want to verify the subnets tied to a specific ELB after getting the name, run this command to list all its subnets:
# For Classic ELB aws elb describe-load-balancers --load-balancer-names YOUR_ELB_NAME --query 'LoadBalancerDescriptions[0].Subnets' # For ALB/NLB aws elbv2 describe-load-balancers --names YOUR_ALB_NAME --query 'LoadBalancers[0].AvailabilityZones[].SubnetId'
内容的提问来源于stack exchange,提问作者Wolverine313

