Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the current user account-id in boto3

Tags:

boto3

botocore

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.

like image 792
Stefano M Avatar asked Oct 25 '15 16:10

Stefano M


People also ask

Which credentials does Boto3 use?

Configuring credentials There are two types of configuration data in Boto3: credentials and non-credentials. Credentials include items such as aws_access_key_id , aws_secret_access_key , and aws_session_token .

What is STS Boto3?

Security Token Service (STS) enables you to request temporary, limited-privilege credentials for Identity and Access Management (IAM) users or for users that you authenticate (federated users).


2 Answers

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

>>> import boto3 >>> boto3.client('sts').get_caller_identity().get('Account') '012345678901' 
like image 117
mixja Avatar answered Sep 21 '22 09:09

mixja


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).

like image 43
Jordon Phillips Avatar answered Sep 21 '22 09:09

Jordon Phillips