[英]Boto3 Missing Contact Tag Values, No Errors
我有这部分脚本应该返回一个联系人值,但脚本正在运行并且没有打印任何联系人值。 我试图将第二个 try 语句向后移动一个缩进,但结果仍然相同。 它应该打印出“instance_contacttag”作为联系人值。 我确定这很简单,但我似乎无法理解,谢谢。
for reservation in reservations:
# tags = {}
for instance in reservation['Instances']:
tags = {}
instance_ids = instance['InstanceId']
print(instance_ids + " is the instance id within the instance_ids dictionary")
try:
for tag in instance['Tags']:
tags[tag['Key']] = tag['Value']
# print(instance['Tags'])
if tag['Key'] == 'Name':
# print(tag['Value'])
instance_nametag = tag['Value']
except:
pass
try:
if tag['Key'] == 'contact':
instance_contacttag = tag['Value']
print(instance_contacttag)
except:
print("CONTACT TAG MISSING")
标签的枚举不会产生异常,这意味着如果该项目不在列表中,您将看不到该项目。
将标签列表转换为字典要容易得多,并执行简单的字典查找以查看是否存在项目:
import boto3
ec2 = boto3.client('ec2')
data = ec2.describe_instances()
reservations = data['Reservations']
for reservation in reservations:
for instance in reservation['Instances']:
tags = instance['Tags']
# Convert the tag list to a Python dictionary to make looking up tags easier
tags = {x['Key']: x['Value'] for x in tags}
# Show the Instance ID
instance_ids = instance['InstanceId']
print(instance_ids + " is the instance id within the instance_ids dictionary")
if 'Name' in tags:
instance_nametag = tags['Name']
print("Name: " + instance_nametag)
# Look for the 'contact' tag
if 'contact' in tags:
instance_contacttag = tags['contact']
print("Contact: " + instance_contacttag)
else:
# It's not present, show a warning
print("CONTACT TAG MISSING")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.