boto3 列出组织中的所有帐户

use*_*mda 4 token boto3 aws-organizations

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

import boto3

client = boto3.client('organizations')
response = client.list_accounts(
    NextToken='string',
    MaxResults=123
)
print(response)
Run Code Online (Sandbox Code Playgroud)

此操作失败并出现以下错误

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

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

小智 12

您可以使用 boto3分页器page

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

session = boto3.session.Session(profile_name=master_acct)
client = session.client('sts')
org = session.client('organizations')
Run Code Online (Sandbox Code Playgroud)

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

paginator = org.get_paginator('list_accounts')
page_iterator = paginator.paginate()
Run Code Online (Sandbox Code Playgroud)

然后遍历帐户的每一页。

for page in page_iterator:        
    for acct in page['Accounts']:
        print(acct) # print the account
Run Code Online (Sandbox Code Playgroud)

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

在上面的部分中,您已经处于每个成员帐户的 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'
)
Run Code Online (Sandbox Code Playgroud)

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

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