Skip to content

Instantly share code, notes, and snippets.

@johngidt
Created June 16, 2016 21:43
Show Gist options
  • Save johngidt/44323648d8eda6eb82ca6010f69f2859 to your computer and use it in GitHub Desktop.
Save johngidt/44323648d8eda6eb82ca6010f69f2859 to your computer and use it in GitHub Desktop.
boto3 Lacks EC2 Instance Identity Metadata Parsing

Given that boto/boto3#313 is not resolved, I hacked together something else in Python that I'm using.

"""
NOTE: This unit test is ONLY good for python 3
"""
import mock
import unittest
class EC2Metadata(unittest.TestCase):
class MockResponse(object):
def __init__(self, resp_data=None, code=200, msg='OK'):
if not resp_data:
resp_data = """{
"devpayProductCodes" : null,
"availabilityZone" : "us-east-1d",
"privateIp" : "10.158.112.84",
"version" : "2010-08-31",
"region" : "us-east-1",
"instanceId" : "i-1234567890abcdef0",
"billingProducts" : null,
"instanceType" : "t1.micro",
"accountId" : "123456789012",
"pendingTime" : "2015-11-19T16:32:11Z",
"imageId" : "ami-5fb8c835",
"kernelId" : "aki-919dcaf8",
"ramdiskId" : null,
"architecture" : "x86_64"
}"""
self.resp_data = resp_data
self.code = code
self.msg = msg
self.headers = {}
def read(self):
return self.resp_data
@mock.patch('urllib.request.urlopen')
def test_parse_ec2_instance_region(self, urlopen):
"""
Check parsing of EC2 instance identity to determine region
TODO: Make test py2 compatible
"""
urlopen.return_value = self.MockResponse()
from util import EC2InstanceIdentity
instance_id = EC2InstanceIdentity()
self.assertEqual(instance_id.region, 'us-east-1')
import json
try:
#py3
from urllib.request import urlopen
except ImportError:
#py2
from urllib2 import urlopen
class EC2InstanceIdentity(object):
"""
Assists in discovery EC2 instance identity info
Ref: http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/instance-identity-documents.html
"""
METADATA_URL = 'http://169.254.169.254/latest/dynamic/instance-identity/document'
"""What URL to hit for the instance identity document"""
def __init__(self):
self._json_document = None
def __fetch_document(self):
"""
Fetches the instance identity document & parses it
"""
raw_document = urlopen(self.METADATA_URL).read()
self._json_document = json.loads(raw_document)
def __getattr__(self, attr_name):
if not self._json_document:
self.__fetch_document()
return self._json_document[attr_name]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment