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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:28:17  来源:igfitidea点击:

Displaying EC2 Instance name using Boto 3

pythonpython-3.xamazon-web-servicesamazon-ec2boto3

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

enter image description here

在此处输入图片说明

I can change ito be i.idor i.instance_typebut when I try nameI get:

我可以更改ii.idi.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 标签的值,您需要查询该标签的实例:

See Obtaining tags from AWS instances with boto

请参阅使用 boto 从 AWS 实例获取标签