Python 使用 Boto 3 显示 EC2 实例名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34751794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Displaying EC2 Instance name using Boto 3
提问by Liondancer
I'm not sure how to display the name of my instance in AWS EC2 using boto3
我不确定如何使用以下命令在 AWS EC2 中显示我的实例名称 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:
我可以更改i
为i.id
或i.instance_type
但当我尝试时,name
我得到:
AttributeError: 'ec2.Instance' object has no attribute 'name'
AttributeError: 'ec2.Instance' object has no attribute 'name'
What is the correct way to get the instance name?
获取实例名称的正确方法是什么?
采纳答案by helloV
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:
如果你想使用 Python 强大的列表理解,一种线性解决方案:
inst_names = [tag['Value'] for i in vpc.instances.all() for tag in i.tags if tag['Key'] == 'Name']
print inst_names
回答by Rodrigo M
In AWS EC2 an instance is taggedwith a Name tag.
在 AWS EC2 中,实例被标记为 Name tag。
In order to get the value of the Name tag for a given instance, you need to query the instance for that tag:
为了获取给定实例的 Name 标签的值,您需要查询该标签的实例: