简体   繁体   中英

Displaying EC2 Instance name using Boto 3

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

In AWS EC2 an instance is tagged with a 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:

See Obtaining tags from AWS instances with boto

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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