In the context of AWS, you can solve and troubleshoot the issue of “unable to get iam security Credentials from EC2 Instance metadata Service” by using these simple steps:-
Checking network’ connection
First, you would need your network connection. Try to verify that there should not be any network ACLs or security groups that are blocking the access.
Verify IAM role
You can try to double-check that the IAM role assigned to the EC2 Instance has the required permissions to access the Resources.
Restart EC2 instance
You can also try to restart the EC2 instance if the issue is persisting.
Here is a simplified example given in Python by using boto 3 to retrieve IAM security credentials from the EC2 instance metadata service:-
Import boto3
Import requests
# Use Boto3 to retrieve IAM credentials
Session = boto3.Session()
Credentials = session.get_credentials()
# Print IAM security credentials
Print(“Access Key:”, credentials.access_key)
Print(“Secret Key:”, credentials.secret_key)
Print(“Session Token:”, credentials.token)
# Alternatively, you can directly access the instance metadata service
Response = requests.get(‘http://169.254.169.254/latest/meta-data/iam/security-credentials/’)
If response.status_code == 200:
Role_name = response.text
Response = requests.get(f’http://169.254.169.254/latest/meta-data/iam/security-credentials/{role_name}’)
Credentials_data = response.json()
Print(“Access Key:”, credentials_data[‘AccessKeyId’])
Print(“Secret Key:”, credentials_data[‘SecretAccessKey’])
Print(“Session Token:”, credentials_data[‘Token’])
Else:
Print(“Unable to access instance metadata service.”)