使用Boto 3显示EC2实例名称 [英] Displaying EC2 Instance name using Boto 3

查看:376
本文介绍了使用Boto 3显示EC2实例名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何使用 boto3

这我有一些代码:

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')

< img src = https://i.stack.imgur.com/uq24o.png alt =在此处输入图片描述>

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

I can change i to be i.id or i.instance_type but when I try name I get:

AttributeError:'ec2.Instance'对象没有属性'name'

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

What is the correct way to get the instance name?

推荐答案

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

There may be other ways. But from your code point of view, the following should work.

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

如果您想使用Python强大的列表理解功能,可以使用一种衬板解决方案:

One liner solution if you want to use Python's powerful list comprehension:

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

这篇关于使用Boto 3显示EC2实例名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆