Caller Identity

I have different AWS accounts for different purposes. One of the account is for just sharing custom AMIs with public. By default, AWS blocks sharing images with public. To enable sharing for all images that are created, I had to run:

Disable Image Block Public Access
$ aws ec2 disable-image-block-public-access --region us-west-2

If you have multiple AWS accounts, it is handy to have a utility that shows you the account ID that is currently being used. This is useful for troubleshooting purposes. Otherwise, things might seem to work in the output but you will not see the resources in the AWS console because your credentials belong to a different AWS account.

Prerequisites

  • You have installed and configured AWS CLI
  • You have installed Python 3.12.0 and boto3 SDK version 1.34.78
  • You are using PyCharm or setup virtual environment for Python

Current Identity

identity.py
import boto3

# Create a session using your current credentials
session = boto3.Session()

# Create an STS client from your session
sts_client = session.client('sts')

# Call the get_caller_identity method
response = sts_client.get_caller_identity()

# Extract the 'Account' key from the response
account_id = response['Account']

print(account_id)

AWS CLI

You can also use AWS CLI command. To output the AWS account ID that the AWS CLI is currently configured to use, run:

AWS CLI command
aws sts get-caller-identity --query "Account" --output text

This command uses the AWS Security Token Service (STS) to retrieve details about the credentials used to call the AWS CLI, including the account ID. The --query "Account" parameter extracts just the account ID from the response, and --output text formats the output as plain text.

Verify Account

You can see the account ID in your AWS console by clicking on your account name at the top right. I use both the code and the AWS CLI to make sure that they are the same. The boto3 code might be picking up different credentials. To see the lookup order for the AWS configuration, you can refer the AWS docs.