Introduction

There are many reasons why you might need your AWS Account ID:

  • If you sign in to an AWS account as an IAM user, you must have your account ID
  • Many AWS resources include the Account ID in their Amazon Resource Names (ARNs).

There are multiple ways to retrieve your Account ID.

Table of contents

How to find Account ID using the AWS CLI?

We will use the sts get-caller-identity command to retrieve the account ID.

aws sts get-caller-identity help

NAME
       get-caller-identity -

DESCRIPTION
       Returns  details  about the IAM user or role whose credentials are used
       to call the operation.

Output:

aws sts get-caller-identity

{
    "UserId": "xxxx",
    "Account": "734xxx",
    "Arn": "arn:aws:iam::734xxxx:user/abhishek"
}

If you want to retrieve only the Account ID, you can use the following command:

aws sts get-caller-identity --query Account

The query filter is used to return only the Account

How to find Account ID using Boto 3?

We can use the get_caller_identity method to retrieve the Account ID.


import boto3

def get_account_id():
    client = boto3.client("sts")
    return client.get_caller_identity()["Account"]


if __name__ == "__main__":
    print(get_account_id())

Output:

734xxx