我的任务:解析“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 正在寻找确切的“名称”并且没有其他变体。在这一点上我很困惑,任何帮助将不胜感激。
三国纷争
相关分类