【问题标题】:AWS - boto3 - how to list of all the ORG IDs(even nested) under organizationAWS - boto3 - 如何列出组织下的所有 ORG ID(甚至嵌套)
【发布时间】:2020-09-16 00:16:58
【问题描述】:

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

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

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

我看过—— 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

但不知道如何互连它们以便它可以找到所有 org 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

【问题讨论】:

标签: python amazon-web-services boto3


【解决方案1】:

简单的解决方案

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)

【讨论】:

    【解决方案2】:

    除了@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
    

    【讨论】:

      【解决方案3】:
      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-13
        • 2020-04-22
        • 2014-06-07
        • 1970-01-01
        • 2014-08-08
        • 1970-01-01
        • 2021-02-19
        • 1970-01-01
        相关资源
        最近更新 更多