Reputation: 185
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?
Upvotes: 9
Views: 14442
Reputation: 9989
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)
Upvotes: 2
Reputation: 2275
With a rather recent aws java sdk you can use getCallerIdentity:
AWSSecurityTokenServiceClientBuilder.standard().build()
.getCallerIdentity(new GetCallerIdentityRequest()).getAccount()
Upvotes: 13
Reputation: 107
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];
Upvotes: 2
Reputation: 107
AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient();
String accountNumber = iamClient.getUser().getUser().getArn().split(":")[4]);
Upvotes: 1
Reputation: 3159
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.
Upvotes: 3
Reputation: 31
look at the account number that is returned in the get_user (iam user) eg,
"Arn": "arn:aws:iam::THISISYOURNUMERICACCOUNTNUMBER:user/lcerezo"
Upvotes: 2