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

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

问题描述

我不确定如何使用 boto3

在 AWS EC2 中显示我的实例名称

这是我的一些代码:

导入boto3ec2 = boto3.resource('ec2', region_name='us-west-2')vpc = ec2.Vpc("vpc-21c15555")对于 vpc.instances.all() 中的 i:打印(一)

我得到的回报是

<代码>.........ec2.Instance(id='i-d77ed20c')

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

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

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

解决方案

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

<预><代码>>>>对于 vpc.instances.all() 中的 i:...对于 i.tags 中的标签:...如果标签['键'] == '名称':...打印标签['值']

如果你想使用 Python 强大的列表推导,一个线性解决方案:

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

I'm not sure how to display the name of my instance in AWS EC2 using boto3

This is some of the code I have:

import boto3

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

What I get in return is

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

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

AttributeError: 'ec2.Instance' object has no attribute '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']

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天全站免登陆