Is it possible to get aws account id with only aws access key and secret key in command line (CLI)
I have access key and secret key with me. Is it possible to get the account id using those in command line.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityThis is the correct way:
~ $ aws sts get-caller-identity
{
"Account": "123456789012",
"UserId": "AIDABCDEFGHJKL...",
"Arn": "arn:aws:iam::123456789012:user/some.user"
}
It works for IAM Users, Cross-account IAM Roles, EC2 IAM Roles, etc.
Use together with jq
to obtain just the account id:
~ $ aws sts get-caller-identity | jq -r .Account
123456789012
$AWS_SECURITY_TOKEN
environment variable set for whatever reason. Run unset AWS_SECURITY_TOKEN AWS_SESSION_TOKEN
first and then retry.
The sts get-access-key-info command lets you get the AWS account ID even if you only know the AWS_ACCESS_KEY_ID
.
$ aws sts get-access-key-info --access-key-id ${AWS_ACCESS_KEY_ID}
{
"Account": "123456789012"
}
Almost every AWS object includes the account id. For example, my IAM user is arn:aws:iam::ACCOUNT_ID:user/Andrew.Lorien, and the ID of one of my cloudformation stacks is arn:aws:cloudformation:us-west-2:ACCOUNT_ID:stack/my-repository/12345678-90ab-cdef-1234-567890abcdef. So you can query anything you know you have, and extract the ID from that. Here's a bash one-liner which gets the first IAM user (a string like arn:aws:iam::ACCOUNT_ID:user/USER_NAME) and extracts the account ID.
aws iam list-users --query "Users[0].Arn" --output text | cut -d ":" -f 5