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

如何通过编程方式批量为AWS sub-accounts添加标签?

批量给AWS子账户添加标签的实现方案

只要你的子账户都归属于AWS Organizations管理,直接调用组织相关的API/CLI即可实现批量打标,你之前用的标签编辑器仅支持扫描各区域的资源级对象,AWS账户属于组织的全局管理对象,因此无法通过标签编辑器直接操作。

以下是两种可直接落地的实现方式:

方式1:AWS CLI 批量操作

操作前请确保你使用的是组织管理账户,或拥有organizations:ListAccounts、organizations:TagResource权限的委托管理员账户。

  1. 先导出所有子账户ID到本地文件,你可以手动编辑该文件剔除不需要打标的账户
aws organizations list-accounts --query 'Accounts[*].Id' --output text > account_ids.txt
  1. 执行批量打标脚本,示例中默认添加两个标签,可根据需求修改标签键值:
#!/bin/bash
# 自定义标签配置
TAG_KEY1="CostCenter"
TAG_VALUE1="operation"
TAG_KEY2="BusinessLine"
TAG_VALUE2="game"

for account_id in $(cat account_ids.txt)
do
  echo "Processing account: $account_id"
  aws organizations tag-resource \
    --resource-id $account_id \
    --tags Key=$TAG_KEY1,Value=$TAG_VALUE1 Key=$TAG_KEY2,Value=$TAG_VALUE2
done

20个账户的情况下全程执行时间不超过1分钟。

方式2:Python Boto3 实现

如果需要自定义匹配逻辑(比如按账户名称自动匹配对应标签值),可以用Python脚本实现:

import boto3

org_client = boto3.client('organizations')
# 自定义标签列表
tags = [
    {"Key": "CostCenter", "Value": "operation"},
    {"Key": "BusinessLine", "Value": "game"}
]

# 获取所有账户列表
accounts = org_client.list_accounts()["Accounts"]
for account in accounts:
    account_id = account["Id"]
    # 如需跳过组织管理账户可加判断:if account_id != "你的管理账户ID"
    print(f"Processing account: {account_id}")
    org_client.tag_resource(
        ResourceId=account_id,
        Tags=tags
    )

注意事项

  • 操作前建议先选1-2个测试账户验证标签规则符合预期后再全量执行
  • 标签键和值需符合AWS标签命名规则,避免使用特殊符号
  • 账户级标签和账户下的资源标签相互独立,账户级标签可直接用于AWS成本账单的分账统计

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:45:02