While running on EC2, the accesskey and secret key can be accessed by the curl command
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/<rolename>
These credentials are not constant and keep changing.
I am wondering if there is a way to get these credentials using the aws-java-sdk
?
I know this can be done using boto3 in python. But don't know how to accomplish the same in java.
Yes, via
EC2MetadataUtils.getIAMSecurityCredentials()
EC2MetadataUtils is a Java adapter for the metadata service that you are accessing via curl, and exposes these fields inEC2MetadataUtils.IAMSecurityCredential
.Signature:
Fields:
To access these fields, use
EC2MetadataUtils.getIAMSecurityCredentials()
:Documentation:
It is outside the scope of this question, but also worth noting that if you are using these credentials for the AWS SDK for Java on this instance that you don't need to define these credentials explicitly -- AWS Clients using the default constructor will search for these credentials as part of the default credentials provider chain. More info in this documentation.