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?
With a rather recent aws java sdk you can use getCallerIdentity:
AWSSecurityTokenServiceClientBuilder.standard().build()
.getCallerIdentity(new GetCallerIdentityRequest()).getAccount()
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"
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];
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With