Skip to content

Commit

Permalink
Merge pull request #28 from ccnmtl/ec2-instance-ip-refactor
Browse files Browse the repository at this point in the history
Refactor get_ec2_instance_ip logic
  • Loading branch information
nikolas authored Aug 15, 2024
2 parents 2fb934b + 3023fb9 commit f3d9a67
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
4 changes: 4 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -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
Expand Down
24 changes: 17 additions & 7 deletions ctlsettings/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,40 @@
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(
token_url,
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 ""


Expand Down

0 comments on commit f3d9a67

Please sign in to comment.