Is there a way to obtain the instance id within an ec2 instance
amazon-ec2, amazon-web-services, backend, python
Solution
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.
Problem
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?