gpt4 book ai didi

python - 使用 boto3 列出主帐户中子帐户的资源?

转载 作者:行者123 更新时间:2023-12-01 07:40:29 25 4
gpt4 key购买 nike

我正在使用 python 和 boto3 列出我的组织拥有的资源。我毫无问题地列出了主帐户中的资源,但我还需要列出子帐户中的资源。我可以获得 child 帐户 ID,但仅此而已。

有什么帮助吗?

最佳答案

您将需要访问属于 child 帐户的一组凭据。

来自Accessing and Administering the Member Accounts in Your Organization - AWS Organizations :

When you create a member account using the AWS Organizations console, AWS Organizations automatically creates an IAM role in the account. This role has full administrative permissions in the member account. The role is also configured to grant that access to the organization's master account.

To use this role to access the member account, you must sign in as a user from the master account that has permissions to assume the role.

因此,您可以在子账户中承担 IAM 角色,然后该角色会提供一组临时凭证,这些凭证可与 boto3 一起使用来对子账户进行 API 调用 child 帐户。

import boto3

role_info = {
'RoleArn': 'arn:aws:iam::<AWS_ACCOUNT_NUMBER>:role/<AWS_ROLE_NAME>',
'RoleSessionName': '<SOME_SESSION_NAME>'
}

client = boto3.client('sts')
credentials = client.assume_role(**role_info)

session = boto3.session.Session(
aws_access_key_id=credentials['Credentials']['AccessKeyId'],
aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
aws_session_token=credentials['Credentials']['SessionToken']
)

一种更简单的方法是将角色作为新配置文件放入 .aws/config 文件中。然后,您可以在进行函数调用时指定配置文件:

# In ~/.aws/credentials:
[master]
aws_access_key_id=foo
aws_secret_access_key=bar

# In ~/.aws/config
[profile child1]
role_arn=arn:aws:iam:...
source_profile=master

像这样使用它:

session = boto3.session.Session(profile_name='dev')
s3 = session.client('s3')

参见:How to choose an AWS profile when using boto3 to connect to CloudFront

关于python - 使用 boto3 列出主帐户中子帐户的资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com