getting the current user account-id in boto3
Asked Answered
D

3

91

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.

Derzon answered 25/10, 2015 at 16:28 Comment(0)
B
186

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

>>> import boto3
>>> boto3.client('sts').get_caller_identity().get('Account')
'012345678901'
Billie answered 9/6, 2016 at 10:23 Comment(3)
This solution is only marginally faster than loading the resource. The only solution I see is to use asynchronous code.Derzon
For some reason this doesn't seem to work anymore. I now get AttributeError: 'STS' object has no attribute 'get_caller_identity'Scribe
After years this method still works. If you have an error like @Mark, check if your user has the right policy.Coffeng
M
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).

Mildred answered 27/10, 2015 at 6:32 Comment(2)
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.Derzon
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.Mildred
U
1
sts            = boto3.client('sts')
AWS_ACCOUNT_ID = sts.get_caller_identity()["Account"]

print(AWS_ACCOUNT_ID)
Unciform answered 29/9, 2022 at 17:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.