在 boto3 中获取当前用户帐户 ID

getting the current user account-id in boto3

我需要得到 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]

但我想知道是否有更 'lightweight' 的方法。事实上

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

实际上我的脚本中不需要 CurrentUser 资源。

编辑:现在有一个 api 您可以调用,请参阅 mixja 的回答。

首先,无法直接从 boto3 获取帐户 ID。没有本地存储的信息可以告诉您这一点,并且在 ARN 上下文之外没有 returns 它的服务 API。因此,如果不检查 ARN,就无法从 boto3 获取它。

其次,对于 boto3botocore 使用 timeit 可能会产生很大的误导,因为在您第一次创建客户端或资源时会有一些预热时间(服务定义是动态加载的)。

您可以使用STS获取账户ID API:

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