diff --git a/os_apply_config/collect.py b/os_apply_config/collect.py new file mode 100644 index 0000000..a188fd2 --- /dev/null +++ b/os_apply_config/collect.py @@ -0,0 +1,27 @@ +import httplib2 +import json + + +EC2_METADATA_URL = 'http://169.254.169.254/latest/meta-data' + + +def _fetch_metadata(sub_url): + h = httplib2.Http() + (resp, content) = h.request('%s%s' % (EC2_METADATA_URL, sub_url)) + if resp.status != 200: + raise Exception('Error fetching %s' % sub_url) + return content + + +def collect_ec2(): + ec2_metadata = {} + root_list = _fetch_metadata('/') + for item in root_list.split("\n"): + ec2_metadata[item] = _fetch_metadata('/%s' % item) + return ec2_metadata + +def __main__(): + print json.dumps(collect_ec2()) + +if __name__ == '__main__': + __main__() diff --git a/os_apply_config/tests/test_collect.py b/os_apply_config/tests/test_collect.py new file mode 100644 index 0000000..1c8db05 --- /dev/null +++ b/os_apply_config/tests/test_collect.py @@ -0,0 +1,47 @@ +import fixtures +import testtools +from testtools import matchers +import urlparse +import uuid + +from os_apply_config import collect + + +META_DATA = {'local-ipv4': '192.0.2.1', + 'reservation-id': uuid.uuid1(), + 'local-hostname': 'foo', + 'ami-launch-index': '0', + 'public-hostname': 'foo', + 'hostname': 'foo', + 'ami-id': uuid.uuid1(), + 'instance-action': 'none', + 'public-ipv4': '192.0.2.1', + 'instance-type': 'flavor.small', + 'instance-id': uuid.uuid1()} + + +class FakeResponse(dict): + status = 200 + + +class FakeHttp(object): + + def request(self, url): + url = urlparse.urlparse(url) + + if url.path == '/latest/meta-data/': + return (FakeResponse(), "\n".join(META_DATA.keys())) + + path = url.path + path = path.replace('/latest/meta-data/', '') + return (FakeResponse(), META_DATA[path]) + + +class TestCollect(testtools.TestCase): + def test_collect_ec2(self): + self.useFixture(fixtures.MonkeyPatch('httplib2.Http', FakeHttp)) + ec2 = collect.collect_ec2() + self.assertThat(ec2, matchers.IsInstance(dict)) + for md_key, md_value in iter(META_DATA.items()): + self.assertIn(md_key, ec2) + self.assertEquals(ec2[md_key], META_DATA[md_key]) diff --git a/requirements.txt b/requirements.txt index a9f8240..2ec6bda 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,6 @@ anyjson argparse d2to1 +httplib2 pbr pystache diff --git a/setup.cfg b/setup.cfg index 8880344..cbc777c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -28,6 +28,7 @@ setup-hooks = console_scripts = os-config-applier = os_apply_config.os_apply_config:main os-apply-config = os_apply_config.os_apply_config:main + os-collect-config = os_apply_config.collect:__main__ [egg_info] tag_build =