You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过boto3获取AWS组织中账号对应的OU名称

获取AWS组织账号对应OU名称的方案

AWS Organizations 没有提供直接传入账号ID即可返回对应OU名称的API方法,你可以通过以下步骤实现需求:

核心思路

  1. 对每个账号,调用list_account_parents接口获取其直接父节点的ID和类型(父节点可能是OU或组织根)
  2. 根据父节点类型,调用对应接口获取名称:
    • 若父节点是OU:用describe_organizational_unit传入OU ID获取名称
    • 若父节点是根:用list_roots获取根节点名称(或直接标记为“组织根”)

代码示例

import boto3

# 初始化Organizations客户端
org_client = boto3.client('organizations')

# 假设你已经获取了账号列表,格式示例:accounts = [{'Id': '123456789012'}, ...]
accounts = []  # 替换为你的账号列表数据

# 预获取根节点信息(可选,用于根节点名称显示)
roots = org_client.list_roots()['Roots']
root_id_to_name = {root['Id']: root['Name'] for root in roots}

# 遍历账号获取对应OU/根名称
for account in accounts:
    account_id = account['Id']
    try:
        # 获取账号的直接父节点
        parents = org_client.list_account_parents(AccountId=account_id)['Parents']
        # 一个账号通常只有一个直接父节点
        if parents:
            parent = parents[0]
            parent_id = parent['Id']
            parent_type = parent['Type']
            
            if parent_type == 'ORGANIZATIONAL_UNIT':
                # 获取OU名称
                ou_info = org_client.describe_organizational_unit(OrganizationalUnitId=parent_id)
                ou_name = ou_info['OrganizationalUnit']['Name']
                print(f"账号 {account_id} 所属OU: {ou_name}")
            elif parent_type == 'ROOT':
                # 获取根节点名称
                root_name = root_id_to_name.get(parent_id, '组织根')
                print(f"账号 {account_id} 所属根节点: {root_name}")
    except Exception as e:
        print(f"获取账号 {account_id} 信息失败: {str(e)}")

补充说明

  • 如果需要获取完整OU路径(比如嵌套OU的层级路径),可以在获取到直接父OU后,递归调用list_parents接口往上遍历,直到根节点,再拼接路径
  • 确保你的IAM身份拥有organizations:ListAccountParents、organizations:DescribeOrganizationalUnit、organizations:ListRoots这些权限

内容的提问来源于stack exchange,提问作者imported

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:11:27