Skip to content

Instantly share code, notes, and snippets.

@iMilnb
Last active February 9, 2020 02:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save iMilnb/ab9939e83168d6df6457e50b0ca73c78 to your computer and use it in GitHub Desktop.
Save iMilnb/ab9939e83168d6df6457e50b0ca73c78 to your computer and use it in GitHub Desktop.
Imports AWS EC2 instance metadata (http://169.254.169.254/latest) into a python dict
#!/usr/bin/env python
import requests
import json
# Converts AWS EC2 instance metadata to a dictionary
def load():
metaurl = 'http://169.254.169.254/latest'
# 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:
return
for l in r.text.split('\n'):
if not l: # "instance-identity/\n" case
continue
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])
else:
r = requests.get(newurl)
if r.status_code != 404:
try:
d[l] = json.loads(r.text)
except ValueError:
d[l] = r.text
else:
d[l] = None
if __name__ == '__main__':
print(json.dumps(load()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment