【问题标题】:Displaying EC2 Instance name using Boto 3使用 Boto 3 显示 EC2 实例名称
【发布时间】:2016-04-17 13:09:17
【问题描述】:

我不确定如何使用 boto3 在 AWS EC2 中显示我的实例名称

这是我的一些代码:

import boto3

ec2 = boto3.resource('ec2', region_name='us-west-2')
vpc = ec2.Vpc("vpc-21c15555")
for i in vpc.instances.all():
    print(i)

我得到的回报是

...
...
...
ec2.Instance(id='i-d77ed20c')

我可以将i 更改为i.idi.instance_type,但是当我尝试name 时,我得到:

AttributeError: 'ec2.Instance' object has no attribute 'name'

获取实例名称的正确方法是什么?

【问题讨论】:

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


    【解决方案1】:

    可能还有其他方法。但从您的代码的角度来看,以下应该可以工作。

    >>> for i in vpc.instances.all():
    ...   for tag in i.tags:
    ...     if tag['Key'] == 'Name':
    ...       print tag['Value']
    

    如果您想使用 Python 强大的列表理解,可以使用一个线性解决方案:

    inst_names = [tag['Value'] for i in vpc.instances.all() for tag in i.tags if tag['Key'] == 'Name']
    print inst_names
    

    【讨论】:

      【解决方案2】:

      在 AWS EC2 中,实例被标记,名称为 tag

      为了获取给定实例的名称标签的值,您需要查询该标签的实例:

      Obtaining tags from AWS instances with boto

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-03
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        • 2013-04-26
        • 2013-07-18
        相关资源
        最近更新 更多