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

如何通过Boto3获取AWS组织或指定组织单元下所有账户的特定标签

实现方法

前置依赖配置

  • Lambda执行角色需附加包含以下权限的IAM策略:
    • organizations:ListAccountsForParent
    • organizations:ListTagsForResource
    • organizations:ListOrganizationalUnitsForParent
  • Lambda需部署在AWS Organizations管理账号,或拥有组织访问权限的委托管理员账号内
  • 提前获取待查询的顶层OU ID(格式为ou-xxxx-xxxxxxxx)、筛选用的标签键与对应值

完整Lambda代码

import boto3

org_client = boto3.client('organizations')

def get_all_nested_ous(parent_ou_id):
    """递归获取指定OU下所有嵌套的子OU ID列表"""
    ous = [parent_ou_id]
    paginator = org_client.get_paginator('list_organizational_units_for_parent')
    for page in paginator.paginate(ParentId=parent_ou_id):
        for ou in page['OrganizationalUnits']:
            # 递归遍历子OU的下级结构
            ous.extend(get_all_nested_ous(ou['Id']))
    return ous

def lambda_handler(event, context):
    # 从调用参数获取配置
    target_ou_id = event['target_ou_id']
    filter_tag_key = event['filter_tag_key']
    filter_tag_value = event['filter_tag_value']
    
    # 获取所有需要遍历的OU列表
    all_ous = get_all_nested_ous(target_ou_id)
    matched_accounts = []
    
    # 遍历所有OU下的账户并筛选标签
    for ou_id in all_ous:
        account_paginator = org_client.get_paginator('list_accounts_for_parent')
        for account_page in account_paginator.paginate(ParentId=ou_id):
            for account in account_page['Accounts']:
                # 拉取当前账户的标签
                tags = org_client.list_tags_for_resource(
                    ResourceId=account['Id']
                )['Tags']
                # 匹配目标标签
                for tag in tags:
                    if tag['Key'] == filter_tag_key and tag['Value'] == filter_tag_value:
                        matched_accounts.append({
                            'AccountId': account['Id'],
                            'AccountName': account['Name'],
                            'AccountArn': account['Arn'],
                            'Status': account['Status']
                        })
                        break
    
    return {
        'statusCode': 200,
        'matched_accounts': matched_accounts,
        'total_count': len(matched_accounts)
    }

使用说明

  • 代码默认使用递归逻辑遍历所有嵌套OU,不会遗漏深层结构下的账户
  • 所有API调用均使用了paginator做分页处理,避免单页返回上限导致的数据缺失
  • 你可以通过Lambda测试事件或者调用接口传入自定义参数,示例入参格式如下:
{
  "target_ou_id": "ou-1234-5678abcd",
  "filter_tag_key": "BusinessCategory",
  "filter_tag_value": "InternalUse"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:57:04