I have an AWS_ACCESS_KEY_ID and an AWS_SECRET_KEY. These are active credentials, so they belong to an active user, who belongs to an AWS Account. How, using Boto3, do I find the ID of this AWS Account?
32
votes
Some methods mentioned here gist.github.com/gene1wood/6d4974b7503336d642c9
- Montaro
Possible duplicate of getting the current user account-id in boto3
- MarnixKlooster ReinstateMonica
@MarnixKlooster This question comes up first on Google for the search "Boto Account ID". Maybe mark the other question as the duplicate.
- Zags
3 Answers
62
votes
5
votes
Thanks to @louahola for the improvement on my initial answer.
This will get you the Account ID for your key pair:
import boto3
sts = boto3.client(
"sts", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY,
)
account_id = sts.get_caller_identity()["Account"]
If you are running on an EC2 instance with IAM role-based permissions or any of boto3's other credential options, you can do this even easier:
import boto3
account_id = boto3.client("sts").get_caller_identity()["Account"]
3
votes
Something like this will work:
import boto3
ACCESS_KEY = 'FOO'
SECRET_KEY = 'BAR'
iam = boto3.resource('iam',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
)
account_id = iam.CurrentUser().arn.split(':')[4]
print account_id
If you use EC2 IAM roles, you can omit all of the access/secret key stuff and the code becomes simply:
iam = boto3.resource('iam')
account_id = iam.CurrentUser().arn.split(':')[4]