问题
I cant find code with boto3. I'm able to get elb name and InstanceID separately but cant link them together to find attached instances to ELB names.
回答1:
Classic Load Balancer
The boto3 describe_load_balancers() functions returns a list of instances:
{
'LoadBalancerDescriptions': [
{
'LoadBalancerName': 'string',
'DNSName': 'string',
....
'Instances': [
{
'InstanceId': 'string'
},
],
....
},
],
'NextMarker': 'string'
}
The Instances
section returns the IDs of the instances for the load balancer.
Application Load Balancer (ELBv2)
This one is harder. The Application Load Balancer has multiple Target Groups. Ports on instances are registered to a Target Group.
The only command that seems to list instances in a Target Group is describe_target_health(), which returns the instance and port (because one instance can serve multiple targets):
{
'TargetHealthDescriptions': [
{
'Target': {
'Id': 'i-0f76fade',
'Port': 80,
},
'TargetHealth': {
'Description': 'Given target group is not configured to receive traffic from ELB',
'Reason': 'Target.NotInUse',
'State': 'unused',
},
},
{
'HealthCheckPort': '80',
'Target': {
'Id': 'i-0f76fade',
'Port': 80,
},
'TargetHealth': {
'State': 'healthy',
},
},
],
'ResponseMetadata': {
'...': '...',
},
}
回答2:
This is my solution which I got it to work. Thank you John.
elbList = boto3.client('elb')
ec2 = boto3.resource('ec2')
bals = elbList.describe_load_balancers()
for elb in bals['LoadBalancerDescriptions']:
print 'ELB DNS Name : ' + elb['DNSName']
for ec2Id in elb['Instances']:
running_instances = \
ec2.instances.filter(Filters=[{'Name': 'instance-state-name'
, 'Values': ['running']},
{'Name': 'instance-id',
'Values': [ec2Id['InstanceId']]}])
for instance in running_instances:
print(" Instance : " + instance.public_dns_name);
回答3:
This is a simple script to find the list of instance attached to an ELB, as an input you may have to provide the ELB name
#!/usr/bin/python
import boto3
import sys
import string
elb_name = raw_input("What is ELB name? :: ")
print ("\n")
print ("THE LIST OF INSTANCES ATTACHED TO THIS ELB IS \n")
elbList = boto3.client('elb')
ec2 = boto3.resource('ec2')
bals = elbList.describe_load_balancers()
for elb in bals['LoadBalancerDescriptions']:
set2 = elb['LoadBalancerName']
if elb_name == set2 :
inst = elb['Instances']
ct = sys.getrefcount(inst)
count = ct
for x in range(count):
iv = elb['Instances'][x]
id = str(iv.values())
id = string.replace(id, "'", "")
print id.strip('[]')
来源:https://stackoverflow.com/questions/42847100/how-to-query-aws-to-get-elb-names-and-attached-instances-to-that-using-python-bo