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?
Asked
Active
Viewed 5.4k times
46
-
Some methods mentioned here https://gist.github.com/gene1wood/6d4974b7503336d642c9 – Montaro Dec 14 '16 at 16:04
-
Possible duplicate of [getting the current user account-id in boto3](https://stackoverflow.com/questions/33332050/getting-the-current-user-account-id-in-boto3) – MarnixKlooster ReinstateMonica Sep 18 '17 at 12:29
-
@MarnixKlooster This question comes up first on Google for the search "Boto Account ID". Maybe mark the other question as the duplicate. – Zags Sep 18 '17 at 13:07
3 Answers
71
The AccountID can be grabbed from the get-caller-identity sts function. This returns an "Account" field:
client = boto3.client("sts", aws_access_key_id=access_key, aws_secret_access_key=secret_key)
account_id = client.get_caller_identity()["Account"]

louahola
- 2,088
- 1
- 15
- 12
22
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"]

Zags
- 37,389
- 14
- 105
- 140
-
You can also set a default for each parameter to None, in which case it retrieves the account number for the current profile, assuming you have that setup. In that way, one can avoid passing around keys and use assumed roles, such as when running on an EC2 instance or via the AWS CLI. – Michael Behrens Dec 08 '20 at 15:19
6
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]

viyh
- 124
- 1
- 6