【问题标题】:EC2 Name tag and its positionEC2 名称标签及其位置
【发布时间】:2020-05-29 11:13:19
【问题描述】:

我有这段代码,它可以工作,但我很快意识到标准不是我们做的事情。在我的代码中,我得到了“名称”的标签值。但是,我这样做的方式是,我假设它是位置 0 的第一个标签。我的假设是错误的。我怎样才能使它更健壮地只查找与位置无关的键“名称”的值?

 response = client.describe_instances(Filters=[{'Name':'tag-key','Values':['Name']}]) 

for item in response['Reservations']:
    #pprint(item['Instances'])
        print("AWS Account ID: {}".format(item['OwnerId']))
        for instance_id in item['Instances']:
            #print(instance_id)
            Tags = instance_id['Tags'][0]['Value']
            State = instance_id['State']['Name']
            print("EC2 Name: {}".format(Tags))
            print("Instance Id is: {}\nInstance Type is: {}".format(instance_id['InstanceId'],instance_id['InstanceType']))

【问题讨论】:

    标签: python python-3.x amazon-web-services amazon-ec2 boto3


    【解决方案1】:

    一种方法是在Tags迭代搜索 以找到KeyName 的标签:

    for item in response['Reservations']:
    
            print("AWS Account ID: {}".format(item['OwnerId']))
    
            for instance_id in item['Instances']:
    
                Tags = instance_id['Tags']
    
                tag_name_value = ""
    
                for tag in Tags:
                    if tag['Key'] == "Name":
                        tag_name_value = tag["Value"]
                        break
    
                State = instance_id['State']['Name']
    
                print("EC2 Name: {}".format(tag_name_value))
                print("Instance Id is: {}\nInstance Type is: {}".format(
                        instance_id['InstanceId'],instance_id['InstanceType']))
    

    【讨论】:

    • 感谢您提供信息。我有一个问题。当我这样做时,我会收到 ec2 实例的所有标签的列表键/值对。我想我可能做错了什么
    • @Randal 你是否也改变了 print: ` print("EC2 Name: {}".format(tag_name_value))`?
    • 正如我所说,我一定是做错了什么...我做错了...谢谢...完美!
    【解决方案2】:

    更多 Pythonic 版本:

    response = ec2_client.describe_instances()
    
    for reservation in response['Reservations']:
        for instance in reservation['Instances']:
            if name := [tag['Value'] for tag in instance['Tags'] if tag['Key'] == 'Name']:
                print(name[0])
    

    或者使用资源方法:

    ec2_resource = boto3.resource('ec2')
    
    for instance in ec2_resource.instances.all():
        if name := [tag['Value'] for tag in instance.tags if tag['Key'] == 'Name']:
            print(name[0])
    

    (需要 Python 3.8)

    【讨论】:

    • 感谢您提供的替代方案。我认为你的例子是列表理解。出于某种原因,这些让我感到困惑。所以我一直坚持寻找答案的漫长道路。
    猜你喜欢
    • 1970-01-01
    • 2016-09-18
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2010-09-17
    • 1970-01-01
    相关资源
    最近更新 更多