简体   繁体   English

使用Boto 3显示EC2实例名称

[英]Displaying EC2 Instance name using Boto 3

I'm not sure how to display the name of my instance in AWS EC2 using boto3 我不确定如何使用boto3在AWS EC2中显示我的实例的名称

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: 我可以改变ii.idi.instance_type但是当我尝试name我得到:

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: 如果你想使用Python强大的列表理解,一个线性解决方案:

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

In AWS EC2 an instance is tagged with a Name tag . 在AWS EC2实例将被上名称标签

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实例获取标记

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM