Python 从 Boto 获取 AWS 账户 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36709461/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get AWS Account ID from Boto
提问by Zags
I have an AWS_ACCESS_KEY_ID and an AWS_SECRET_KEY. These are active credentials, so they belong to an active user, who belongs to an AWS Account. How, using Boto3, do I find the ID of this AWS Account?
我有一个 AWS_ACCESS_KEY_ID 和一个 AWS_SECRET_KEY。这些是活动凭证,因此它们属于属于 AWS 账户的活动用户。如何使用 Boto3 找到此 AWS 账户的 ID?
回答by louahola
The AccountID can be grabbed from the get-caller-identity sts function. This returns an "Account" field:
AccountID 可以从 get-caller-identity sts 函数中获取。这将返回一个“帐户”字段:
client = boto3.client("sts", aws_access_key_id=access_key, aws_secret_access_key=secret_key)
account_id = client.get_caller_identity()["Account"]
回答by Zags
The following function will get you the Account ID for your key pair:
以下函数将为您提供密钥对的帐户 ID:
import boto3
def get_aws_account_id(access_key, secret_key):
sts = boto3.client(
"sts", aws_access_key_id=access_key, aws_secret_access_key=secret_key,
)
user_arn = sts.get_caller_identity()["Arn"]
return user_arn.split(":")[4]
This works because user ARN is of the format "arn:aws:iam::ACCOUNT_ID:user/USERNAME". Splitting by colons, Account ID is the 4th item (0-indexed).
这是有效的,因为用户 ARN 的格式为“arn:aws:iam::ACCOUNT_ID:user/USERNAME”。按冒号拆分,帐户 ID 是第 4 项(0 索引)。
回答by viyh
Something like this will work:
像这样的事情会起作用:
import boto3
ACCESS_KEY = 'FOO'
SECRET_KEY = 'BAR'
iam = boto3.resource('iam',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
)
account_id = iam.CurrentUser().arn.split(':')[4]
print account_id
If you use EC2 IAM roles, you can omit all of the access/secret key stuff and the code becomes simply:
如果您使用 EC2 IAM 角色,您可以省略所有访问/密钥内容,代码变得简单:
iam = boto3.resource('iam')
account_id = iam.CurrentUser().arn.split(':')[4]