Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to obtain the instance id within an ec2 instance [duplicate]

I try to launch a service on ec2 instance. the service is supposed to send out the id of the instance. I know this could be obtained using something like curl http://0.0.0.0/latest/meta-data. is there any other ways that you could directly get the meta data maybe from the instance shell or some APIs in python?

like image 673
Wang Nick Avatar asked May 06 '17 02:05

Wang Nick


People also ask

Is EC2 instance ID globally unique?

Your instance IDs are globally unique, for as long as you have access to the resource.

Can we duplicate EC2 instance?

To do this, open the EC2 console, select the instance that you want to duplicate, and then choose the Image | Create Image commands from the Actions menu.

How do I find out my instance ID?

In the navigation pane, select Instances. The Instances page opens. Click the instance that you want the ID for. The instance details page opens and displays the ID and IP address.


1 Answers

Amazon EC2 instance metadata can be accessed via:

http://169.254.169.254/latest/meta-data/

To retrieve the ID of the instance from which that request is made:

http://169.254.169.254/latest/meta-data/instance-id/

This can be retrieved by curl, wget, web browser or anything that makes a call to retrieve an HTTP page.

If you wish to do it programmatically, here's some code from boto3 equivalent to boto.utils.get_instance_metadata()?:

# Python2
import urllib2
instanceid = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read()

# Python3
import urllib.request
instanceid = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode()

There is also a boto.utils.get_instance_metadata() call in boto (but not boto3) that returns the instance metadata as a nested Python dictionary.

like image 133
John Rotenstein Avatar answered Sep 17 '22 10:09

John Rotenstein