How to get accesskey, secretkey using java aws SDK running on EC2

2.9k views Asked by At

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.

2

There are 2 answers

7
Anthony Neace On BEST ANSWER

Yes, via EC2MetadataUtils.getIAMSecurityCredentials() EC2MetadataUtils is a Java adapter for the metadata service that you are accessing via curl, and exposes these fields in EC2MetadataUtils.IAMSecurityCredential.

Signature:

public static class EC2MetadataUtils.IAMSecurityCredential

Fields:

String accessKeyId 
String secretAccessKey 

To access these fields, use EC2MetadataUtils.getIAMSecurityCredentials():

public static Map<String,EC2MetadataUtils.IAMSecurityCredential> 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.

0
user2434291 On

Here is a working example

// This prints the EC2 instance role and then the keys
void printCredentials() {
    Map<String,EC2MetadataUtils.IAMSecurityCredential> credMap = EC2MetadataUtils.getIAMSecurityCredentials();
    Iterator<Map.Entry<String,EC2MetadataUtils.IAMSecurityCredential>> it = credMap.entrySet().iterator();
    while (it.hasNext()) {
        // First print the role associated with this instance
        Map.Entry<String,EC2MetadataUtils.IAMSecurityCredential> pair = (Map.Entry<String,EC2MetadataUtils.IAMSecurityCredential>)it.next();
        System.out.println("Role: " + pair.getKey() + " = Value: " + pair.getValue());

        // Next print the access key and secret key
        EC2MetadataUtils.IAMSecurityCredential cred = pair.getValue();
        System.out.println("Access key: " + cred.accessKeyId + ", Secret key: " + cred.secretAccessKey);
    }
}