无法从aws组织获取整个组织单位列表

2024-05-01 21:37:59 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的代码,用于从根到最后一个单位获取组织单位名称 但这只适用于3个级别 比如说,在我的组织里

Root/one/two/three/{AWS帐户} Root/car/bike/twoweeler/{AWS账户}

我期待从上面的输出

根/一/二/三 Root/汽车/自行车/两轮车

但我只得到了以下(它只返回到3级)

根/一/二 根/汽车/自行车


import boto3

client = boto3.client('organizations')
list_roots = client.list_roots()
root_id = list_roots['Roots'][0]['Id']
root_name = list_roots['Roots'][0]['Name']
oulist = client.list_organizational_units_for_parent(ParentId=root_id)
aws_acc_ou_path = {}

for ou in oulist['OrganizationalUnits']:
    ou_path = root_name
    ou_id = ou['Id']
    ou_name = ou['Name']
    ou_path = ou_path + "/" + ou_name
    org_unit_info = client.list_organizational_units_for_parent(ParentId=ou_id)

    while True:
          for oui in org_unit_info['OrganizationalUnits']:
              org_id = oui['Id']
              ou_path = ou_path + "/" + oui['Name']
          if 'NextToken' in org_unit_info:
             org_unit_info = client.list_organizational_units_for_parent(ParentId=ou_id, NextToken=org_unit_info['NextToken'])
          else:
             break
    #print (ou_path)

Tags: pathnameorginfoclientidforunit
1条回答
网友
1楼 · 发布于 2024-05-01 21:37:59

这里有几个问题。第一个是,当需要N deep时,最好将其设计为递归函数。第二项需要注意的是,组织API的最大值非常低(20?),因此您的第一次调用可能会遗漏一些OU。我更喜欢使用分页器,因为它使我更干净

我修改了一些现有的代码,我相信这将为您工作

org_client = boto3.client('organizations')
account_list = util_org.accounts_with_ou_path(org_client, 'r-xxxx', '/')
print(account_list)

def accounts_with_ou_path(org_client: boto3.client, ou_id: str, path: str) -> list:
    """ Return list of accounts at this OU as well as deeper """
    ou_list = []

    # I. Get further children ous
    paginator = org_client.get_paginator('list_children')
    pages = paginator.paginate(
        ParentId=ou_id,
        ChildType='ORGANIZATIONAL_UNIT'
    )
    for page in pages:
        for child in page['Children']:
            ou_list.extend(accounts_with_ou_path(org_client, child['Id'], path+ou_id+'/'))

    # II. Get Accounts located at ou
    pages = paginator.paginate(
        ParentId=ou_id,
        ChildType='ACCOUNT'
    )
    for page in pages:
        for child in page['Children']:
            ou_list.append(path+ou_id+'/'+child['Id'])

    return ou_list

相关问题 更多 >