8

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.

3 Answers 3

8

This 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
7
  • An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid Getting this error :(
    – Vandhana
    Nov 12, 2018 at 6:02
  • That's because you've got $AWS_SECURITY_TOKEN environment variable set for whatever reason. Run unset AWS_SECURITY_TOKEN AWS_SESSION_TOKEN first and then retry.
    – MLu
    Nov 12, 2018 at 6:04
  • Getting same error :|
    – Vandhana
    Nov 12, 2018 at 7:48
  • i got the output.. but for the below command AWS_ACCESS_KEY_ID=AXXXXXXGA AWS_SECRET_ACCESS_KEY=NXXXXXXt aws sts get-caller-identity But y shd i specify the keys for all the aws commands.. is there any other way to do so
    – Vandhana
    Nov 12, 2018 at 7:57
  • @Vandhana you can save the credentials to a config file: docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html
    – MLu
    Nov 12, 2018 at 8:16
2

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"
}
0

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
2
  • An error occurred (InvalidClientTokenId) when calling the ListUsers operation: The security token included in the request is invalid Getting this error
    – Vandhana
    Nov 12, 2018 at 5:42
  • Hmm, you must not have permission to read IAM, even your own. I have a better answer, but it's a completely different answer so I'll post it separately. Nov 12, 2018 at 23:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .