From 3023fb98fb6b48a982189f117f3607bb448a7ed7 Mon Sep 17 00:00:00 2001 From: Nikolas Nyby Date: Thu, 15 Aug 2024 13:29:00 -0400 Subject: [PATCH] Refactor get_ec2_instance_ip logic I've refactored the `try` blocks to only contain the lines which would fail with the expected exception. This is the general best practice we use with try/except. --- CHANGES.txt | 4 ++++ ctlsettings/shared.py | 24 +++++++++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/CHANGES.txt b/CHANGES.txt index e4f1e43..f89a73d 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,7 @@ +0.3.3 +==================== +* Added token process to get_ec2_instance_ip() + 0.3.2 (2024-04-16) ==================== * Added CSRF_TRUSTED_ORIGINS config for Django >= 4.0 diff --git a/ctlsettings/shared.py b/ctlsettings/shared.py index 6b63cad..3ca3986 100644 --- a/ctlsettings/shared.py +++ b/ctlsettings/shared.py @@ -3,11 +3,13 @@ import requests -def get_ec2_instance_ip(): +def get_ec2_instance_ip() -> str: # URL to retrieve the token for IMDSv2 token_url = "http://169.254.169.254/latest/api/token" # URL to get the local IPv4 address ipv4_url = "http://169.254.169.254/latest/meta-data/local-ipv4" + + token_response = None try: # Get the token required for accessing IMDSv2 token_response = requests.put( @@ -15,18 +17,26 @@ def get_ec2_instance_ip(): headers={"X-aws-ec2-metadata-token-ttl-seconds": "21600"}, timeout=2 ) - if token_response.status_code == 200: - token = token_response.text - else: - return "" # Token request failed + except requests.exceptions.RequestException: + return "" + + token = None + if token_response.status_code == 200: + token = token_response.text + else: + return "" # Token request failed + response = None + try: # Use the token to access the IPv4 metadata response = requests.get( ipv4_url, headers={"X-aws-ec2-metadata-token": token}, timeout=2) - if response.status_code == 200: - return response.text except requests.exceptions.RequestException: return "" + + if response.status_code == 200: + return response.text + return ""