Skip to content

Instantly share code, notes, and snippets.

@ystoneman
Last active December 28, 2021 20:04
Show Gist options
  • Save ystoneman/3cdc09dac3fae2db236e382f8e671dc0 to your computer and use it in GitHub Desktop.
Save ystoneman/3cdc09dac3fae2db236e382f8e671dc0 to your computer and use it in GitHub Desktop.
Vipin Ajayakumar (bluprince13)'s script, adapted to include /dynamic. The script gets all the output from EC2 instance metadata and outputs it in json format
import requests
import json
metadata_url = 'http://169.254.169.254/latest/'
def expand_tree(url, arr):
output = {}
for item in arr:
new_url = url + item
r = requests.get(new_url)
text = r.text
if item[-1] == "/":
list_of_values = r.text.splitlines()
output[item[:-1]] = expand_tree(new_url, list_of_values)
elif is_json(text):
output[item] = json.loads(text)
else:
output[item] = text
return output
def get_data(path):
initial = [path]
result = expand_tree(metadata_url, initial)
return result
def get_data_json(path):
metadata = get_data(path)
metadata_json = json.dumps(metadata, indent=4, sort_keys=True)
return metadata_json
def is_json(myjson):
try:
json.loads(myjson)
except ValueError:
return False
return True
if __name__ == '__main__':
print(get_data_json("meta-data/"))
print(get_data_json("dynamic/"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment