Skip to content

Instantly share code, notes, and snippets.

@j1v37u2k3y
Last active August 17, 2022 17:44
Show Gist options
  • Save j1v37u2k3y/6bd994c0ae271e3450636963fe717242 to your computer and use it in GitHub Desktop.
Save j1v37u2k3y/6bd994c0ae271e3450636963fe717242 to your computer and use it in GitHub Desktop.
get all data from ec2 metadata
#!/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(), indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment