Could you share the ec2_metadata code?
Based on the issue, it’s likely that either there’s a core logic error or your EC2 instance is using IMDSv2, while the code might be trying to fetch the metadata using the IMDSv1 approach.
this is how to get the metadata with python using IMDSv1
import requests
def get_metadata_v1():
url = "http://169.254.169.254/latest/meta-data/"
try:
response = requests.get(url, timeout=2)
response.raise_for_status()
return response.text
except requests.exceptions.RequestException as e:
print(f"Failed to fetch metadata using IMDSv1: {e}")
return None
print(get_metadata_v1())
and this is how to get it using IMDSv2
import requests
def get_metadata_v2():
base_url = "http://169.254.169.254/latest/meta-data/"
token_url = "http://169.254.169.254/latest/api/token"
try:
# Step 1: Get the token
token_response = requests.put(
token_url, headers={"X-aws-ec2-metadata-token-ttl-seconds": "21600"}, timeout=2
)
token_response.raise_for_status()
token = token_response.text
# Step 2: Use the token to fetch metadata
metadata_response = requests.get(
base_url, headers={"X-aws-ec2-metadata-token": token}, timeout=2
)
metadata_response.raise_for_status()
return metadata_response.text
except requests.exceptions.RequestException as e:
print(f"Failed to fetch metadata using IMDSv2: {e}")
return None
print(get_metadata_v2())