Skip to content

Instantly share code, notes, and snippets.

@doublenns
Last active October 18, 2019 06:15
Show Gist options
  • Save doublenns/481e08ec2c989bdcc28389e60bd44ed0 to your computer and use it in GitHub Desktop.
Save doublenns/481e08ec2c989bdcc28389e60bd44ed0 to your computer and use it in GitHub Desktop.
Retrieve EC2's region from instance metadata using Python
import requests
import sys
from requests.packages.urllib3 import Retry
def get_instance_region():
instance_identity_url = "http://169.254.169.254/latest/dynamic/instance-identity/document"
session = requests.Session()
retries = Retry(total=3, backoff_factor=0.3)
metadata_adapter = requests.adapters.HTTPAdapter(max_retries=retries)
session.mount("http://169.254.169.254/", metadata_adapter)
try:
r = requests.get(instance_identity_url, timeout=(2, 5))
except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError) as err:
print("Connection to AWS EC2 Metadata timed out: " + str(err.__class__.__name__))
print("Is this an EC2 instance? Is the AWS metadata endpoint blocked? (http://169.254.169.254/)")
sys.exit(1)
response_json = r.json()
region = response_json.get("region")
return(region)
@doublenns
Copy link
Author

doublenns commented Oct 18, 2019

From an EC2 instance:

>>> region = get_instance_region()
>>> print(region)
us-east-2

From system that isn't an EC2 instance:

>>> region = get_instance_region()
Connection to AWS EC2 Metadata timed out: ConnectTimeout
Is this an EC2 instance? Is the AWS metadata endpoint blocked? (http://169.254.169.254/) 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment