gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 19:56:02 25 4
gpt4 key购买 nike

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

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

这个结构将来可能会改变,更多的 ORG 单元可能会被添加,其中一些可能会被删除,所以我想让这个函数变得动态。我希望我可以提供根 ID,之后它应该能够找到其下的所有组织 ID。但这似乎有点复杂,因为 boto3 中没有现有的 API 可以列出 root 下的所有 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

最佳答案

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

关于python - AWS - boto3 - 如何列出组织下的所有 ORG ID(甚至嵌套),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57012709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com