這裏是一個工作示例
// 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);
}
}
嗯該類似乎並沒有對這些領域的任何干將?我將如何訪問它們?例如...我想簡單地將它們打印到標準輸出。 – Anthony
FWIW,我需要訪問這些憑據,因爲我的代碼使用第三方庫來訪問S3資源,這些庫需要accesskey和secretkey才能訪問資源。我的計劃是從AWS SDK獲取它們並將它們傳遞給第三方庫。 – Anthony
@Anthony使用'EC2MetadataUtils.getIAMSecurityCredentials()'。更新回答,並附有適當的文檔鏈接 –