AWS-Boto3-如何在组织下列出所有ORG ID(甚至嵌套)

时间:2019-07-12 19:02:14

标签: python amazon-web-services boto3

我正在尝试使用boto3获取组织下所有组织ID的列表。当前的结构是这样的-

                          Root
                            |
                            |
                    ou1-----OU2-----OU3
                     |      |        |
                    ou4    ou5      ou6
                     |
                    ou7
                     |
                    ou8

此结构将来可能会更改,可能会添加更多的ORG单元,其中一些可能会删除,因此我想使函数动态化。我希望我可以提供Root ID,之后它应该能够找到其下的所有组织ID。但这似乎有点复杂,因为boto3中没有现有的API,该API列出了根目录下的所有ORG ID。如果有人可以提供指导/建议,我将不胜感激

我看过- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/organizations.html#Organizations.Client.list_children

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/organizations.html#Organizations.Client.list_parents

但不确定如何互连它们,以便可以找到所有组织ID,以下是我编写的代码,但这只会获取第二层子级,直到org4,5和6为止

org = session.client("organizations")
    response = org.list_roots()
    for PolicyTypes in response["Roots"]:
        parent_id = PolicyTypes["Id"]
    OUlist = []
    NextToken = False
    while NextToken is not None:
        if not NextToken:
            response_iterator = org.list_organizational_units_for_parent(ParentId=parent_id, MaxResults=20)
        else:
            response_iterator = org.list_organizational_units_for_parent(ParentId=parent_id, MaxResults=20,
                                                                         NextToken=NextToken)
        OUlist = get_OUlist(OUlist, response_iterator)
        try:
            NextToken = response_iterator['NextToken']
        except KeyError:
            break

    get_child_ou(org, OUlist)



def get_child_ou(org, OUlist):
    for ou in OUlist:
        NextToken = False
        while NextToken is not None:
            if not NextToken:
                response_iterator = org.list_children(ParentId=ou, ChildType='ORGANIZATIONAL_UNIT', MaxResults=20)
            else:
                response_iterator = org.list_children(ParentId=ou, ChildType='ORGANIZATIONAL_UNIT', NextToken=NextToken,
                                                      MaxResults=20)
            try:
                NextToken = response_iterator['NextToken']
            except KeyError:
                break
    for orgid in response_iterator["Children"]:
        OUlist.append(orgid["Id"])
    return OUlist

3 个答案:

答案 0 :(得分:2)

简单的解决方案

import boto3

session = boto3.Session(profile_name='default')
org = session.client('organizations')


def printout(parent_id, indent):
    print(f"{'-' * indent} {parent_id}")
    paginator = org.get_paginator('list_children')
    iterator = paginator.paginate(
        ParentId=parent_id,
        ChildType='ORGANIZATIONAL_UNIT'
    )
    indent += 1
    for page in iterator:
        for ou in page['Children']:
            printout(ou['Id'], indent)
    

if __name__ == "__main__":
    rootid = org.list_roots()["Roots"][0]["Id"]
    printout(rootid, 0)

答案 1 :(得分:0)

import boto3

def add_ou(ids):
    for id in ids:
        ou_list.append(id)
        child_ids = get_childs(id)
        while child_ids:
            if len(child_ids) > 1:
                add_ou(child_ids)
                child_ids = []
            else:
                ou_list.append(child_ids[0])
                child_ids = get_childs(child_ids[0])

def get_childs(id):
    childs = org_client.list_children(
    ParentId=id,
    ChildType='ORGANIZATIONAL_UNIT')
    return [child["Id"] for child in childs["Children"]]

if __name__ == "__main__":
    org_client = boto3.client('organizations')
    root_id = org_client.list_roots()["Roots"][0]["Id"]
    childs = get_childs(root_id)
    ou_list = []
    add_ou(childs)
    print(ou_list)

这将遍历所有组织单位和打印组织单位ID

答案 2 :(得分:0)

除了@Danish的答案:

您现在可以将Paginator功能用于 organizations.list_children (以及许多其他API调用)。这样就无需检查NextToken,节省了LOC,并增强了代码的可读性:-)

# Lambda example
import boto3

client = boto3.client('organizations')

def lambda_handler(event, context):
  root_id    = client.list_roots()['Roots'][0]['Id']
  ou_id_list = get_ou_ids(root_id)

  print(ou_id_list)


def get_ou_ids(parent_id):
  full_result = []

  paginator = client.get_paginator('list_children')
  iterator  = paginator.paginate(
    ParentId=parent_id,
    ChildType='ORGANIZATIONAL_UNIT'
  )

  for page in iterator:
    for ou in page['Children']:
      # 1. Add entry
      # 2. Fetch children recursively
      full_result.append(ou['Id'])
      full_result.extend(get_ou_ids(ou['Id']))

  return full_result