本文介绍了boto3列出组织中的所有帐户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要求列出所有帐户,然后将所有凭据写入~/.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
文件中使用哪些凭据?推荐答案
您可以使用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资源。
这篇关于boto3列出组织中的所有帐户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!