获取未使用的负载均衡器列表

时间:2019-10-22 13:47:03

标签: python amazon-web-services amazon-elb

我正在尝试列出未使用的负载均衡器(elb)。我正在尝试以下代码,并且抛出错误

“属性错误”:“ str”对象没有属性“ describe_instance_health()”


import boto3

elb = boto3.client('elb')

allElbs = elb.describe_load_balancers()
print (allElbs)
for lb in allElbs:
    instances = lb.describe_instance_health()
    if len(instances)==0:
        print (lb)
    for instanceState in instances:
        if  instanceState.state == 'OutOfService':
            print (lb)

请帮助我解决这个问题。 谢谢 enter image description here

更新代码:

import boto3

elb = boto3.client('elb')

allElbs = elb.describe_load_balancers()
#print (allElbs)
for lb in allElbs['LoadBalancerDescriptions']:
    #instances = elb.describe_instance_health(lb['LoadBalancerName'])
    #instances = elb.describe_instance_health(['LoadBalancerName'])
    instances = elb.describe_instance_health(LoadBalancerName=lb['LoadBalancerName'])

    if len(instances)==0:
        print (lb)
    for instanceState in instances:
        if  instanceState == 'OutOfService':
            print (lb)

1 个答案:

答案 0 :(得分:3)

下面。对describe_load_balancers()的调用返回一个字典。在字典中,您可以找到磅的列表。参见herehere

import boto3


def filter_lbs():
    """ return a list of lb's that has no instances or in state OutOfService"""
    result = []
    elb = boto3.client('elb')
    lbs = elb.describe_load_balancers()
    for lb in lbs['LoadBalancerDescriptions']:
        instances = elb.describe_instance_health(LoadBalancerName=lb['LoadBalancerName'])['InstanceStates']
        if not instances:
            result.append(lb['LoadBalancerName'])
            continue
        for instance in instances:
            if instance['State'] == 'OutOfService':
                result.append(lb['LoadBalancerName'])
                continue
    return result