我的任务:解析“aws ec2 describe-instances”json 输出的输出以收集各种实例详细信息,包括分配给实例的“名称”标签。我的代码摘录:# Query AWS ec2 for instance information my_aws_instances = subprocess.check_output("/home/XXXXX/.local/bin/aws ec2 describe-instances --region %s --profile %s" % (region, current_profile), shell=True) # Convert AWS json to python dictionary my_instance_dict = json.loads(my_aws_instances) # Pre-enter the 'Reservations' top level dictionary to make 'if' statement below cleaner. my_instances = my_instance_dict['Reservations'] if my_instances: for my_instance in my_instances: if 'PublicIpAddress' in my_instance['Instances'][0]: public_ip = my_instance['Instances'][0]['PublicIpAddress'] else: public_ip = "None" if 'PrivateIpAddress' in my_instance['Instances'][0]: private_ip = my_instance['Instances'][0]['PrivateIpAddress'] else: private_ip = "None" if 'Tags' in my_instance['Instances'][0]: tag_list = my_instance['Instances'][0]['Tags'] for tag in tag_list: my_tag = tag.get('Key') if my_tag == "Name": instance_name = tag.get('Value') else: instance_name = "None" state = my_instance['Instances'][0]['State']['Name'] instance_id = my_instance['Instances'][0]['InstanceId'] instance_type = my_instance['Instances'][0]['InstanceType']以下是“tag”变量循环时包含的内容的示例。这是一个python字典:{'Value': 'server_name01.domain.com', 'Key': 'Name'}一切正常,除了“标签”部分在某些情况下有效,在其他情况下无效,即使我正在测试的“名称”值在所有情况下都存在。换句话说,在某些确实具有“名称”标签和名称的实例上,我得到“无”。我已经排除了服务器名称本身的问题,即空格和特殊字符与结果有关。我还尝试确保 python 正在寻找确切的“名称”并且没有其他变体。在这一点上我很困惑,任何帮助将不胜感激。
1 回答
三国纷争
TA贡献1804条经验 获得超7个赞
你这里有一个逻辑问题:
for tag in tag_list:
my_tag = tag.get('Key')
if my_tag == "Name":
instance_name = tag.get('Value')
else:
instance_name = "None"
假设您有一个带有两个标签的实例,
[
{
"Key": "Name",
"Value": "My_Name"
},
{
"Key": "foo",
"Value": "bar"
}
]
当它遍历 for 循环时,它将首先评估Name: My_Name键值对并设置instance_name为My_Name,但是 for 循环将继续运行,当它评估第二个键值对时,它将设置instance_name为None,覆盖先前分配的值.
一种简单的解决方案是在找到Name密钥后退出 for 循环,例如:
for tag in tag_list:
my_tag = tag.get('Key')
if my_tag == "Name":
instance_name = tag.get('Value')
break
else:
instance_name = "None"
添加回答
举报
0/150
提交
取消