Identify AWS Account and IAM User You Are Working using CLI Tool
In this AWS CLI tutorial, I want to show how aws sts get-caller-identity is use to identify the AWS IAM user or AWS IAM role you are working with on your cloud platform account. While you are executing AWS CLI commands, you may want to know the IAM user or IAM role the code is executed by programmatically. This AWS guide will show cloud engineers how to find the AWS account id, user id and IAM role by executing AWS CLI commands.
In general, get-caller-identity method of sts AWS CLI command will returns details about the AWS account, IAM user or IAM role whose credentials are being used to execute the current CLI command. The cloud user can query the output of the get-caller-identity method to fetch the required information as shown in following sections.
For example, I executed below command on an AWS Lab environment on a Cloud9 terminal
The output of the AWS CLI command is as follows, since the lab environment is not valid any more I can share freely
As seen in the output, there is an Account information returning the account id or account number. Additionally, we have the UserId information and the assumed IAM role by the Cloud9 environment, EC2 instance is visible in the ARN number.
{
"UserId": "AROAWDLQMJIIWEQ5END5B:e77ff3c2-8360-483e-a1b3-5b4ceb0a6d96",
"Account": "419531868689",
"Arn": "arn:aws:sts::419531868689:assumed-role/AWSLabsUser-urLyK49dgA4iP2xSUjt32K/e77ff3c2-8360-483e-a1b3-5b4ceb0a6d96"
}
Find Current AWS Account Id by Executing AWS CLI Command
If the cloud engineer wants to get the current AWS account id by programmatically, following AWS CLI command will help.
This command will return the 12-digit AWS account id data as output
In a bash script, you can read account id into a variable and read the value from stored variable as follows
Find Current AWS User Id by Running AWS CLI Command
The same solution can be used for fetching the current AWS user id, following AWS CLI command can be used for accessing AWS user id programmatically.
For more parameter arguments to AWS CLI command get-caller-identity, please refer to official documentation from Amazon Web Services.