Last active
October 18, 2019 06:15
-
-
Save doublenns/481e08ec2c989bdcc28389e60bd44ed0 to your computer and use it in GitHub Desktop.
Retrieve EC2's region from instance metadata using Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From an EC2 instance:
From system that isn't an EC2 instance: