在 boto3 中,在哪里放置"if"语句以仅输出具有空数组的值?



我使用的是aws-boto3,对编码&必须找到如何深入我的输出,只返回没有目标连接的负载平衡器/目标组。

def gettargets(arn):
tglist=elb.describe_target_health(TargetGroupArn=arn)
targets=[]
for targetid in tglist["TargetHealthDescriptions"]:
targets.append(targetid['Target']['Id']) 
print("Targets:",targets)
elbs = elb.describe_load_balancers(PageSize=100)
for loadbalancer in elbs["LoadBalancers"]:
print("n"*2)
print("-"*8)
print("ELB Name:",loadbalancer["LoadBalancerName"])
print("Type:",loadbalancer["Type"])
print("Scheme:",loadbalancer["Scheme"])
print("TargetGroups:",str(gettargetgroups(loadbalancer["LoadBalancerArn"])))
for tgs in gettargetgrouparns(loadbalancer["LoadBalancerArn"]):
gettargets(tgs)

输出看起来像

--------
ELB Name: example-elb
Type: application
Scheme: internet-facing
TargetGroups: ['example-tg']
Targets: ['i-09876543210']
--------
ELB Name: example-alb-2
Type: application
Scheme: internal
TargetGroups: ['example-tg-2']
Targets: []

我需要帮助返回空目标的部分:[]

我应该在getargets函数中放入if语句,还是在底部为生成if语句。我可以读python,但还没有能够概念化结构和这些部分是如何工作的。

您实际上并没有在这里"返回"任何内容,您只是在获得结果时立即将结果转储到屏幕上。

拆分逻辑和打印,就有了。

def gettargets(arn):
tglist=elb.describe_target_health(TargetGroupArn=arn)
targets=[]
for targetid in tglist["TargetHealthDescriptions"]:
targets.append(targetid['Target']['Id']) 
# now we return, not print!
return targets

elbs = elb.describe_load_balancers(PageSize=100)
for loadbalancer in elbs["LoadBalancers"]:

targets = []
for tgs in gettargetgrouparns(loadbalancer["LoadBalancerArn"]):
targets += gettargets(tgs)
# print the whole stuff only if targets is empty
if targets == []:
print("n"*2)
print("-"*8)
print("ELB Name:",loadbalancer["LoadBalancerName"])
print("Type:",loadbalancer["Type"])
print("Scheme:",loadbalancer["Scheme"])
print("TargetGroups:", str(gettargetgroups( loadbalancer["LoadBalancerArn"])))
print("Targets:",targets)

您只需从gettargets返回targets,然后检查其是否为空:

def gettargets(arn):
tglist=elb.describe_target_health(TargetGroupArn=arn)
targets=[]
for targetid in tglist["TargetHealthDescriptions"]:
targets.append(targetid['Target']['Id']) 
return targets

elbs = elb.describe_load_balancers(PageSize=100)
for loadbalancer in elbs["LoadBalancers"]:
targets = []

for tgs in gettargetgrouparns(loadbalancer["LoadBalancerArn"]):
targets += gettargets(tgs)
if not targets:
print("n"*2)
print("-"*8)
print("ELB Name:",loadbalancer["LoadBalancerName"])
print("Type:",loadbalancer["Type"])
print("Scheme:",loadbalancer["Scheme"])
print("TargetGroups:",str(gettargetgroups(loadbalancer["LoadBalancerArn"])))
print("Targets:",  targets)

相关内容

  • 没有找到相关文章

最新更新