Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get AWS account details using java api? Not for IAM user

We have two AWS accounts. One is for production and another is for testing. We need to differentiate the environment we are running. We can see that a simple way is to get account name and once we get that it will be very straight forward. But, we don't know how to get it from AWS credentials or properties. Does anyone have idea about how to get account information using AWS credentials? I considered the possibility of account permissions, account type etc, but I think it should not prevent us from getting account name?

like image 524
Pramod Gaikwad Avatar asked Dec 16 '15 08:12

Pramod Gaikwad


5 Answers

With a rather recent aws java sdk you can use getCallerIdentity:

AWSSecurityTokenServiceClientBuilder.standard().build()
    .getCallerIdentity(new GetCallerIdentityRequest()).getAccount()
like image 161
Steven Avatar answered Oct 21 '22 16:10

Steven


You can see the GetUserResult. This is returned by getUser(). GetUserResult has a method to get User. This User has all the fields to get the required information you need.

like image 28
phoenix Avatar answered Oct 21 '22 14:10

phoenix


look at the account number that is returned in the get_user (iam user) eg,

"Arn": "arn:aws:iam::THISISYOURNUMERICACCOUNTNUMBER:user/lcerezo"

like image 38
lcerezo Avatar answered Oct 21 '22 16:10

lcerezo


In case you are using the Secured Token Service, you will not be able to get the user details to get the account number. You can instead use the role. Below is the sample code.

AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient();
GetRoleRequest getRoleRequest = new GetRoleRequest();
getRoleRequest.setRoleName("roleName");
String accountNumber = iamClient.getRole(getRoleRequest).getRole().getArn().split(":")[4];
like image 22
SheoSinha Avatar answered Oct 21 '22 16:10

SheoSinha


Using the AWS v2.0 Java SDK, you can use software.amazon.awssdk.services.sts.StsClient#getCallerIdentity.

First add a dependency to the sts module, eg in gradle:

implementation platform("software.amazon.awssdk:bom:2.14.2")
implementation "software.amazon.awssdk:sts"

Then:

log.info("{}", StsClient.create().getCallerIdentity());

will return:

GetCallerIdentityResponse(UserId=AJAIVBQXMUAJAIVBQXMU, Account=298232720644, Arn=arn:aws:iam::298232720644:user/adrian)

like image 45
Adrian Baker Avatar answered Oct 21 '22 15:10

Adrian Baker