Skip to content

Instantly share code, notes, and snippets.

@imShakil
Last active September 22, 2025 10:36
Show Gist options
  • Select an option

  • Save imShakil/97f0b1156129bacd7d6b513dbc593a9f to your computer and use it in GitHub Desktop.

Select an option

Save imShakil/97f0b1156129bacd7d6b513dbc593a9f to your computer and use it in GitHub Desktop.
display aws instance info
from flask import Flask
import socket
import requests
app = Flask(__name__)
IMDS_URL = "http://169.254.169.254/latest"
TOKEN_URL = f"{IMDS_URL}/api/token"
def get_metadata(path):
headers = {}
try:
token = requests.put(
TOKEN_URL,
headers={"X-aws-ec2-metadata-token-ttl-seconds": "21600"},
timeout=2
).text
headers = {"X-aws-ec2-metadata-token": token}
except requests.RequestException:
pass
try:
return requests.get(f"{IMDS_URL}/meta-data/{path}", headers=headers, timeout=2).text
except requests.RequestException:
return "N/A"
@app.route("/")
def server_info():
return f"""
<h1>Server Details</h1>
<p><b>Instance ID:</b> {get_metadata("instance-id")}</p>
<p><b>Availability Zone:</b> {get_metadata("placement/availability-zone")}</p>
<p><b>Private IP:</b> {get_metadata("local-ipv4")}</p>
<p><b>Public IP:</b> {get_metadata("public-ipv4")}</p>
<p><b>Hostname:</b> {socket.gethostname()}</p>
"""
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment