Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor get_ec2_instance_ip logic #28

Merged
merged 1 commit into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading