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?
-
aws has resource group function, it will help you for your problem. – BMW Dec 16 '15 at 09:22
-
Thanks @BMW, got a point. – Pramod Gaikwad Dec 16 '15 at 11:32
-
1answered at http://stackoverflow.com/questions/10197784/how-can-i-deduce-the-aws-account-id-from-available-basicawscredentials – phoenix Dec 17 '15 at 11:39
-
Thanks @Sri.U, the link is useful specially when user does not have access **getUser()** then we can get account id by parsing **error** message. – Pramod Gaikwad Dec 17 '15 at 15:45
6 Answers
With a rather recent aws java sdk you can use getCallerIdentity:
AWSSecurityTokenServiceClientBuilder.standard().build()
.getCallerIdentity(new GetCallerIdentityRequest()).getAccount()

- 2,050
- 23
- 20
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.
look at the account number that is returned in the get_user (iam user) eg,
"Arn": "arn:aws:iam::THISISYOURNUMERICACCOUNTNUMBER:user/lcerezo"

- 31
- 3
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];

- 107
- 4
-
1Not the best approach, but works for me. Hope amazon guys are reading such posts and will add getAccountId to the API. – Vadim Jan 30 '17 at 07:58
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)

- 9,297
- 1
- 26
- 22
AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient();
String accountNumber = iamClient.getUser().getUser().getArn().split(":")[4]);

- 107
- 4