37

In regular boto 2.38 I used to access instance metadata (e.g. get current stack-name), through boto's

boto.utils.get_instance_metadata()

Is there an equivalent in boto3, or do I need to go to the down level direct http address to fetch metadata about the running instance?

0

3 Answers 3

18

Nope, still no equivalent in boto3, just hit this gap myself.
They have an open feature request for this https://github.com/boto/boto3/issues/313 that references this question.

As for workarounds,
you can continue to use boto.utils or use urllib/urllib2 to do the HTTP requests manually ie.

# 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()

see What is the quickest way to HTTP GET in Python? for a quick intro on urllib and http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-instance-metadata.html#instancedata-data-categories for the URI structure of the metadata service.

3
  • 6
    is this still true?! siiiiiiigh
    – dwanderson
    Jan 10, 2018 at 20:13
  • @dwanderson Unfortunately Yes !
    – jimy
    Mar 8, 2018 at 12:55
  • Additionally you can use the adamchainz/ec2-metadata package. It would have to be pip installed so is perhaps not ideal for Lambda but this package is simple to use.
    – jarmod
    Jan 7, 2020 at 16:33
3

You could use the third-party library ec2-metadata.

Here an example from the docs showing how to get your EC2 region:

  pip install ec2-metadata

  >>> from ec2_metadata import ec2_metadata
  >>> print(ec2_metadata.region)
  us-east-1
2

You can fetch specific metadata from the the IMDSFetcher in botocore:

from botocore.utils import IMDSFetcher

IMDSFetcher()._get_request("/latest/meta-data/instance-type", None).text

This will also work on instances where IMDSv2 is enforced.

1
  • This does not work fir IMDSv2 enforced enviroments. as a third argument token=IMDSFetcher()._fetch_metadata_token() must be given. otherwise this is the only valid answer to the origin question!
    – Markus
    Jan 18 at 8:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.