Skip to content

Instantly share code, notes, and snippets.

@iMilnb iMilnb/
Last active May 27, 2019

What would you like to do?
Imports AWS EC2 instance metadata ( into a python dict
#!/usr/bin/env python
import requests
import json
# Converts AWS EC2 instance metadata to a dictionary
def load():
metaurl = ''
# those 3 top subdirectories are not exposed with a final '/'
metadict = {'dynamic': {}, 'meta-data': {}, 'user-data': {}}
for subsect in metadict.keys():
datacrawl('{0}/{1}/'.format(metaurl, subsect), metadict[subsect])
return metadict
def datacrawl(url, d):
r = requests.get(url)
if r.status_code == 404:
for l in r.text.split('\n'):
if not l: # "instance-identity/\n" case
newurl = '{0}{1}'.format(url, l)
# a key is detected with a final '/'
if l.endswith('/'):
newkey = l.split('/')[-2]
d[newkey] = {}
datacrawl(newurl, d[newkey])
r = requests.get(newurl)
if r.status_code != 404:
d[l] = json.loads(r.text)
except ValueError:
d[l] = r.text
d[l] = None
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.