我有两个账户:
- 账户A(主账户/管理账户(
- 账户B(会员账户(
我在帐户B(成员帐户(中部署了一个Lambda函数,该函数列出了组织中的所有帐户。以下是Lambda函数代码:
import boto3
import json
org_client = boto3.client('organizations')
org_id='o-ib1qmgzn48'
def lambda_handler(event, context):
account_list = []
def list_aws_accounts_for_ou(ou_id):
# add accounts in the current/root OU
try:
lafp_paginator = org_client.get_paginator('list_accounts_for_parent')
lafp_page_iterator = lafp_paginator.paginate(ParentId=org_id)
for page in lafp_page_iterator:
for acct in page['Accounts']:
account_list.append(acct)
except org_client.exceptions.ClientError as error:
print(f'Error: {error}')
# add accounts in child ous
try:
lc_paginator = org_client.get_paginator('list_children')
ou_page_iterator = lc_paginator.paginate(
ParentId=org_id,
ChildType='ORGANIZATIONAL_UNIT'
)
for page in ou_page_iterator:
for child in page['Children']:
print(f"Adding accounts from child OU {child['Id']}")
account_list += list_aws_accounts_for_ou(child['Id'])
except org_client.exceptions.ClientError as error:
print(f'Error: {error}')
print(f"Found {len(account_list)} accounts in Oraganization {org_id}")
return json.loads(json.dumps(account_list, default=str))
此Lambda函数具有一个具有以下权限的角色(GetAccountsListLambdaRole(:Lambda基本执行角色在账户a(管理/主账户(中扮演角色的内联策略
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": "sts:AssumeRole",
"Resource": "arn:aws:iam::Account A:role/OrganizationsReadAssumeRole"
}
}
帐户A中的"OrganizationsReadAssumeRole"具有以下权限和信任策略:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"organizations:ListAccounts",
"organizations:ListAccountsForParent",
"organizations:ListChildren"
],
"Resource": "*"
}
]
}
信任策略是:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::Account B:role/GetAccountsListLambdaRole"
},
"Action": "sts:AssumeRole",
"Condition": {}
}
]
}
当我运行Lambda函数时,我会得到以下错误:
Error: An error occurred (AccessDeniedException) when calling the ListAccountsForParent operation: You don't have permissions to access this resource.
Error: An error occurred (AccessDeniedException) when calling the ListChildren operation: You don't have permissions to access this resource.
我有几个问题:
- 无论我在尝试什么-从会员帐户获取帐户列表;有可能吗?如果是,我如何解决上述错误和实现这一点
请帮忙。
您需要实际承担lambda中的OrganizationsReadAssumeRole
角色。这个博客有一个例子:
sts_connection = boto3.client('sts')
acct_a = sts_connection.assume_role(
RoleArn="arn:aws:iam::222222222222:role/OrganizationsReadAssumeRole",
RoleSessionName="cross_acct_lambda"
)
ACCESS_KEY = acct_a['Credentials']['AccessKeyId']
SECRET_KEY = acct_a['Credentials']['SecretAccessKey']
SESSION_TOKEN = acct_a['Credentials']['SessionToken']
# create service client using the assumed role credentials, e.g. S3
org_client = boto3.client(
'organizations',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
aws_session_token=SESSION_TOKEN,
)
... # rest of your code
将222222222222
替换为您的功能所承担的跨帐户角色的AWS帐户ID。