【问题标题】:boto3 list all accounts in an organizationboto3 列出组织中的所有帐户
【发布时间】:2020-05-22 18:08:17
【问题描述】:

我需要列出所有帐户,然后将所有凭据写入我的~/.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 文件中使用什么凭据?

【问题讨论】:

  • 评论 NextToken='string', #NextToken='string',
  • 没有任何区别,它从哪里读取凭据?

标签: token boto3 aws-organizations


【解决方案1】:

您可以使用 boto3 分页器页面

使用主账户中的 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 资源。

【讨论】:

  • 谢谢,这很有用,但是运行它会给我一个错误,我无权执行“assumerole”操作
猜你喜欢
  • 2023-04-06
  • 2018-10-13
  • 1970-01-01
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
相关资源
最近更新 更多