getting the current user account-id in boto3

Stefano M picture Stefano M · Oct 25, 2015 · Viewed 31.1k times · Source

I need to get the account-id of the 'current user' in a boto3 script. Up to now my best solution is to parse the current user arn:

>>> import boto3
>>> account_id = boto3.resource('iam').CurrentUser().arn.split(':')[4]

but I was wondering if there is a more 'lightweight' approach. In fact

>>> timeit.timeit("boto3.resource('iam').CurrentUser().arn",
... 'import boto3', number=10)
4.8895583080002325

and I actually do not need the CurrentUser resource in my script.

Answer

mixja picture mixja · Jun 9, 2016

You can get the account ID by using the STS API:

>>> import boto3
>>> boto3.client('sts').get_caller_identity().get('Account')
'012345678901'