2

我有一个要求,我想列出所有帐户,然后在我的~/.aws/credentials文件中写入所有凭据。我正在使用boto3以下方式

import boto3

client = boto3.client('organizations')
response = client.list_accounts(
    NextToken='string',
    MaxResults=123
)
print(response)

这失败并出现以下错误

botocore.exceptions.ClientError: An error occurred (ExpiredTokenException) when calling the ListAccounts operation: The security token included in the request is expired

问题是,它在看哪个令牌?如果我想要有关所有帐户的信息,我应该在credentials文件或config文件中使用什么凭据?

4

1 回答 1

7

您可以使用 boto3分页器pages

使用主账户中的 aws 配置文件获取组织对象:

session = boto3.session.Session(profile_name=master_acct)
client = session.client('sts')
org = session.client('organizations')

然后使用 org 对象获取分页器。

paginator = org.get_paginator('list_accounts')
page_iterator = paginator.paginate()

然后遍历帐户的每一页。

for page in page_iterator:        
    for acct in page['Accounts']:
        print(acct) # print the account

我不确定您所说的“获取凭据”是什么意思。您无法获取其他人的凭据。您可以做的是列出用户,如果需要,然后列出他们的访问密钥。这将要求您在每个成员帐户中担任一个角色。

在上述部分中,您已经在每个成员帐户的 for 循环中。你可以这样做:

id = acct['Id']
role_info = {
    'RoleArn': f'arn:aws:iam::{id}:role/OrganizationAccountAccessRole',
    'RoleSessionName': id
}


credentials = client.assume_role(**role_info)

member_session = boto3.session.Session(
    aws_access_key_id=credentials['Credentials']['AccessKeyId'],
    aws_secret_access_key=credentials['Credentials']['SecretAccessKey'],
    aws_session_token=credentials['Credentials']['SessionToken'],
    region_name='us-east-1'
)

但是请注意,指定的角色OrganizationAccountAccessRole需要实际存在于每个帐户中,并且您的主帐户中的用户需要具有担任此角色的权限。

设置好先决条件后,您将遍历每个帐户,并在每个帐户中使用member_session来访问该帐户中的 boto3 资源。

于 2020-05-22T10:08:17.607 回答