Find AWS Account Id using CLI or Boto3

How to find the AWS Account ID using the AWS CLI or Boto3?

AWS CLI

Retrieve your full identity

1
aws sts get-caller-identity
1
2
3
4
5
{
    "UserId": "AIDA...",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/user"
}

Use native AWS CLI --query option for querying the output.

1
aws sts get-caller-identity --query "Account" --output text
1
123456789012

Python Boto3

1
2
3
4
5
import boto3

sts = boto3.client("sts")
account_id = sts.get_caller_identity()["Account"]
print(account_id) # 0123456789012