Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying EC2 Instance name using Boto 3

Tags:

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

enter image description here

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?

like image 826
Liondancer Avatar asked Jan 12 '16 19:01

Liondancer


People also ask

How do I find my EC2 instance hostname?

You can see the hostname values for an existing EC2 instance in the Details tab for the EC2 instance: Hostname type: The hostname in IP name or resource name format. Private IP DNS name (IPv4 only): The IP name that will always resolve to the private IPv4 address of the instance.

How do I know my EC2 instance type?

To find an instance type using the consoleOpen the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . From the navigation bar, select the Region in which to launch your instances. You can select any Region that's available to you, regardless of your location. In the navigation pane, choose Instance Types.


1 Answers

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 
like image 182
helloV Avatar answered Oct 02 '22 01:10

helloV