79

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.

Stefano M
  • 4,267
  • 2
  • 27
  • 45

3 Answers3

168

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

>>> import boto3
>>> boto3.client('sts').get_caller_identity().get('Account')
'012345678901'
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
mixja
  • 6,977
  • 3
  • 32
  • 34
  • 1
    This solution is only marginally faster than loading the resource. The only solution I see is to use asynchronous code. – Stefano M Jul 27 '16 at 14:39
  • 1
    For some reason this doesn't seem to work anymore. I now get `AttributeError: 'STS' object has no attribute 'get_caller_identity'` – Mark Aug 24 '16 at 00:53
  • 1
    After years this method still works. If you have an error like @Mark, check if your user has the right policy. – Cv4niak Jun 27 '22 at 08:37
1

EDIT: There is now an api you can call, see mixja's answer.

First off, there is no way to get the account id straight from boto3. There is no information stored locally that can tell you that, and there is no service API that returns it outside the context of an ARN. So there is no way to get it from boto3 without inspecting an ARN.

Secondly, using timeit can be very misleading with boto3 or botocore because there is a bit of warm-up time when you create a client or resource for the first time (the service definitions are loaded on the fly).

Jordon Phillips
  • 14,963
  • 4
  • 35
  • 42
  • Thanks for the answer, but let me add that I know that in `boto3` the attributes are lazily evaluated, so that the first access takes longer than the subsequent ones. The point is that my script is used interactively as a CLI, and a delay of about 500ms on the first access results in a "laggish" user experience. – Stefano M Oct 27 '15 at 12:54
  • mixja, this answer was correct at the time of writing. The operation used in your answer was added on April 5th, 2016. I edited my comment to point to your answer. – Jordon Phillips Oct 25 '16 at 19:05
1
sts            = boto3.client('sts')
AWS_ACCOUNT_ID = sts.get_caller_identity()["Account"]

print(AWS_ACCOUNT_ID)
ADV-IT
  • 756
  • 1
  • 8
  • 10