AWS boto3如何列出组织下的所有组织ID(甚至嵌套)

2024-04-26 07:00:15 发布

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

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

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

这种结构将来可能会改变,更多的组织单位可能会被添加,有些可能会被删除,所以我想使功能动态化。我希望我可以提供根id,之后它应该能够找到它下面的所有org id。但这似乎有点复杂,因为boto3中没有列出根下所有组织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

但不确定如何将它们连接起来,这样它就可以找到所有的orgid,下面是我编写的代码,但这只会获取第二层的子层,即直到org4、5和6

^{pr2}$

Tags: httpscomapiidhtmldocumentationserviceboto3
1条回答
网友
1楼 · 发布于 2024-04-26 07:00:15
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

相关问题 更多 >