6

I can able to get the load balancers using below

import boto3
elb = boto3.client('elbv2')
lbs = elb.describe_load_balancers()

How to get the instances of the lbs.

Also How Can I fetch the load balancers which state is not active as describe_load_balanacers only give state active load balanceres.

Rajarshi Das
  • 11,778
  • 6
  • 46
  • 74
  • What do you mean by "instances of the LBs"? Do you mean the list of instances to which the load balancer sends requests? What type of load balancer are you using — Classic, Application or Network? If it is the Application Load Balancer, then you would have to go to the Target Groups and get the instances from them. – John Rotenstein Jul 09 '18 at 11:38
  • Hi Jhon Thank you for your reply I am using classic and I want the instances where it sends requests – Rajarshi Das Jul 09 '18 at 11:49
  • Also Can you guide me how can I get ec2 instances of application load balancers as well by using target groups – Rajarshi Das Jul 09 '18 at 11:51

2 Answers2

14

Classic Load Balancer

Use: client = boto3.client('elb')

Then describe_load_balancers() results include a list of instances:

        'Instances': [
            {
                'InstanceId': 'string'
            },
        ],

Application Load Balancer

Use: client = boto3.client('elbv2')

Here is a sample response:

{
    'TargetHealthDescriptions': [
        {
            'Target': {
                'Id': 'i-0f76fade',
                'Port': 80,
            },
...
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
1

for anyone looking for a quick snippet to see if your instance is in the LB:

from ec2_metadata import ec2_metadata
instance_id: str = ec2_metadata.instance_id
import boto3
client = boto3.client("elbv2" , region_name="us-west-2")

response = client.describe_target_groups(
        LoadBalancerArn="your arn goes here"
)
target_group_arn = response["TargetGroups"][0]["TargetGroupArn"]

response = client.describe_target_health(TargetGroupArn=target_group_arn)

instances = map(lambda x: x["Target"]["Id"], response["TargetHealthDescriptions"])

print(f"target group instances {list(instances)}")
print(f"this instance {instance_id}")
foobar8675
  • 1,215
  • 3
  • 16
  • 26