AWS Builder Center
Tag a Multi-Account AWS Org in an Afternoon with AI

Tag a Multi-Account AWS Org in an Afternoon with AI

Use Resource Explorer bulk tagging, account tags and any AI coding agent you already use (Claude Code, Codex or Kiro) to backfill tags safely, without fighting Terraform drift.

  • Tag your accounts first. Account tags now work as cost allocation tags and cover every metered charge in the account, including charges you can't tag. If your accounts map to environments, that answers "what does Dev cost?" on its own.
  • Let an agent do the inference, with read-only access. It proposes tags in a CSV, you approve the rows you trust, and a 59-line script applies them. I tested this end to end with Claude Code and Codex on 20 messy resources.
  • Fix the source, then lock it in. Terraform  default_tags  for anything Terraform manages, bulk tagging for the rest, then tag policies, an SCP and AWS Config so new resources arrive tagged.

Why now

I keep having the same conversation with startups. They run an AWS Organization, usually on Control Tower, with a few years of Terraform and console clicks behind it. Then the CFO asks what the development accounts cost, or security asks who owns a bucket, and nobody can answer because nothing is tagged.
Until recently, fixing that meant weeks of scripts and spreadsheets. Three changes cut it to an afternoon:
  1. Resource Explorer bulk tagging (2 November 2026). Tag Editor now redirects to Resource Explorer. You run one search, select up to 400 resources, choose Actions → Manage tags, and tag them across Regions in one step. ( launch post )
  1. Account tags as cost allocation tags (December 2025). You tag an account in AWS Organizations, activate the tag in Billing, and it applies to all metered usage in that account. ( What's New  ·  docs )
  1. AI coding agents. Working out the  Owner  or  Application  of 3,000 resources means matching names, CloudTrail events and Terraform state. Agents do that well. The  AWS MCP Server , generally available since May 2026 as part of the  Agent Toolkit for AWS , gives them IAM-controlled, CloudTrail-logged access to AWS APIs and documentation. They need to read, not write, so they only get read access.

Before you tag anything

Decide what each tag is for. Cost allocation, ownership, automation and security need different keys. If you can't name the question a tag answers, leave it out.
Start with five keys or fewer:
Key
Example values
Used for
 Environment 
 dev ,  test ,  prod 
Cost, automation, SCPs
 Owner 
a team name, never a person's personal data
Ownership
 Application 
 orders ,  billing 
Cost
 CostCenter 
 cc-1234 
Finance
 Schedule 
 office-hours 
Instance Scheduler
Write the keys down with exact casing. Tag keys are case-sensitive, so  environment  and  Environment  show up as two different keys in your bill and in tag policies.
Tag the accounts first. If your accounts are already split by environment or by customer, tag each account in AWS Organizations (for example  Environment=dev ) and activate the tag for cost allocation. That covers every metered charge in the account, including data transfer and other items that can't carry a resource tag. You still need resource tags for shared resources inside an account, and for automation such as scheduling.

How it fits together


Resource Explorer org view feeds a read-only AI agent, which writes a proposed tags CSV; a human app

The rule is simple: the agent proposes, a human approves, a script applies.
  • The agent has read-only permissions. It inventories resources and writes a CSV of proposed tags, with a source and a confidence level for each row.
  • You review the CSV and mark the rows you approve.
  • A short script applies only the approved rows. It never removes a tag.
A wrong guess costs you review time, not a broken bill.

One-time setup

1. Resource Explorer. Turn it on across the Organization with  Systems Manager Quick Setup . It creates an index in every Region and an  aggregator index  for cross-Region search. Then create a  multi-account view  in your delegated administrator account.
Use the multi-account view to find resources. AWS doesn't document tagging other accounts' resources from that view, and the  TagResources API  only tags resources in the account and Region you call it from. Plan to tag one account at a time: in that account's console, or with the script assuming a role in each account.
2. Two roles in every member account. Deploy them with  CloudFormation StackSets  or  AFT account customisations .
  •  TagReadOnly  is for the agent. It covers Resource Explorer read,  tag:Get* , CloudTrail  LookupEvents , CloudFormation describe and list, and  iam:ListRoleTags . The   ListResources  API  is authorised by  resource-explorer-2:Search ; there's no separate IAM action for it.
  •  TagWriter  is for the apply script only, run from your machine or a pipeline, never from the agent's session. It allows  tag:TagResources  and the service tag actions behind it. It has no untag actions and no  cloudformation:UpdateStack .
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "InventoryReadOnly",
"Effect": "Allow",
"Action": [
"resource-explorer-2:Search",
"resource-explorer-2:GetView",
"resource-explorer-2:GetDefaultView",
"resource-explorer-2:ListViews",
"resource-explorer-2:GetIndex",
"resource-explorer-2:ListIndexes",
"resource-explorer-2:ListSupportedResourceTypes",
"tag:GetResources",
"tag:GetTagKeys",
"tag:GetTagValues",
"cloudtrail:LookupEvents",
"cloudformation:DescribeStacks",
"cloudformation:ListStackResources",
"cloudformation:DescribeStackResources",
"cloudformation:ListStacks",
"iam:ListRoleTags"
],
"Resource": "*"
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "TaggingApi",
"Effect": "Allow",
"Action": [
"tag:TagResources",
"tag:GetResources"
],
"Resource": "*"
},
{
"Sid": "ServiceTagActionsUsedByTagResources",
"Effect": "Allow",
"Action": [
"s3:GetBucketTagging",
"s3:PutBucketTagging",
"sqs:TagQueue",
"sqs:ListQueueTags",
"sns:TagResource",
"dynamodb:TagResource",
"logs:TagResource",
"logs:TagLogGroup",
"ssm:AddTagsToResource",
"ec2:CreateTags",
"lambda:TagResource",
"iam:TagRole"
],
"Resource": "*"
}
]
}
Add service actions for the services you run, for example  rds:AddTagsToResource  or  elasticloadbalancing:AddTags .

Step 1: Inventory

Start in Resource Explorer to size the problem. This finds everything in a project that has no cost centre:
tagdemo -tag.key:CostCenter


Resource Explorer search results for resources missing a CostCenter tag, account details masked


Testing this taught me two things:
  • Tag filters ignore case.  tag.key:Environment  also matches  environment , and  tag.value:dev  matches  Dev . A  -tag.key:Environment  search therefore hides resources with the wrong casing, even though your bill and your tag policies treat them as different keys. Use Resource Explorer to find resources, and check exact keys with the Tagging API's  GetResources .
  • Scripts should call  ListResources , not  Search .  Search  returns at most 1,000 results, and the console says so: keyword queries are limited to 1,000 results, so use queries without keywords for a wider inventory.  ListResources  has no cap, but it only accepts filter operators such as  region: ,  resourcetype:  and  tag.key: , so apply name filters yourself.
In my sandbox, new resources took up to 3 minutes to appear in search.

Step 2: Let the agent propose

The agent gets a runbook and some context, and writes a CSV.
You provide:
  • Your tag schema, with exact casing and allowed values.
  • An account ID to environment map, for example  111122223333,dev .
  • Optionally, a principal-to-team map for owners, and the ARNs in Terraform state ( terraform show -json ).
The runbook below works as  AGENTS.md  for Codex, as  CLAUDE.md  (or imported from it) for Claude Code, and as a steering file in Kiro. Give the agent the  TagReadOnly  credentials and nothing else.

Tag backfill runbook (agent proposes, human approves, script applies)

Inputs (in ./inputs/, supplied by a human):
- schema.json: tag keys with exact casing and allowed values, e.g. {"Environment": ["dev","test","prod"], "Application": ["orders","billing"], "Owner": []}. An empty list means free text.
- accounts.csv: account_id,environment. owners.csv (optional): principal_substring,owner.
- tf_arns.txt (optional): one ARN per line, from terraform show -json.
- In the prompt: the Regions, the aggregator Region, and the scope (for example "ARN or Name tag contains shop-").

Hard rules:
1. Read-only. Use only Resource Explorer list-resources/search, tag:GetResources, cloudtrail:LookupEvents, iam list-role-tags and CloudFormation describe-*/list-*. Never call Tag*, Untag*, Create*, Put* or Delete*, and never write tags yourself.
2. Never invent an Owner. Propose Owner only from an existing tag (owner, team) or from owners.csv matched against the CloudTrail creator. Otherwise write no Owner row and list the resource under "Needs owner".
3. Use the key casing in schema.json exactly. Normalise values to the allowed list (Dev, development become dev). Propose a non-Environment key only if exactly one allowed value appears as a token in the name (the resource name, or its Name tag when the ARN holds only an ID, as for security groups).
4. Never overwrite a schema key that already has an allowed value. If evidence conflicts (for example a tag says prod but the account is dev), propose the account-map value with confidence=low and list every source.
5. IaC-managed resources: set managed_by=cloudformation if the resource is a stack, has an aws:cloudformation:stack-name tag, or its physical ID appears in aws cloudformation list-stack-resources for any stack. Some types (SQS) get no aws:cloudformation tags, so build that list once per Region. Set managed_by=terraform if the ARN is in tf_arns.txt or has ManagedBy=terraform. Still write the rows, so a human can fix the code. The apply script skips them.

Steps:
1. Inventory with aws resource-explorer-2 list-resources --region <aggregator> --filters FilterString="region:<r>" (and region:global). It has no 1,000-result cap but rejects free text, so apply name scopes yourself to the ARN and the Name tag. Resource Explorer tag filters ignore case, so never use them to decide compliance.
2. Get exact tags with aws resourcegroupstaggingapi get-resources --resource-arn-list (per Region, up to 100 ARNs). ARNs it omits have no tags, except IAM roles, which it never returns, so use aws iam list-role-tags for those.
3. For each resource, gather evidence:
- Name tokens (dev, prod, application names).
- The account's environment from accounts.csv.
- Existing alias tags in any casing (env, Env, environment, stage for Environment; app for Application; team for Owner).
- The CloudTrail creator: aws cloudtrail lookup-events --lookup-attributes AttributeKey=ResourceName,AttributeValue=<name, or queue URL for SQS>, oldest Create* event. Only the last 90 days are available, and there are 2 calls per second per Region.
- The IaC checks in rule 5.
4. Confidence: high means the account map decides Environment and nothing conflicts. medium means one source (a name token, an alias tag, or CloudTrail plus owners.csv). low means a conflict.
5. Write proposed_tags.csv with the header account_id,region,arn,key,value,source,confidence,managed_by. Use one row per resource and key, and only for keys that are missing or invalid. source is short, for example account-map=dev;tag Env=Dev. Use us-east-1 as the region for global resources.
6. Write proposed_tags_summary.md: counts by confidence, managed_by and key; "Needs owner"; conflicts; resources whose tags get-resources cannot read back (IAM roles: TagResources can tag them, but verify with aws iam list-role-tags); and the alias keys to remove later (the script never untags).
7. Stop. Apply nothing. Never propose tags for a CloudFormation stack itself: TagResources on a stack runs a stack update. A human adds an approved column (yes or blank) and runs apply_tags.py.

I tested it against 20 resources across two Regions, tagged badly on purpose:  env ,  Env=Dev ,  environment=development , an  Environment=Prod  bucket in a dev account, and 7 resources with no tags. Claude Code proposed 48 rows: 16 high confidence, 30 medium and 2 low. The 2 low rows were the real conflicts. It flagged 4 rows as IaC-managed and listed 5 resources that need an owner, because CloudTrail had no creator for them.
I then gave Codex the same runbook and the same read-only evidence. It proposed the same 48 rows and caught a case I'd missed: a security group whose ARN holds only an ID, so its application name had to come from the  Name  tag. That fix is in the runbook above.

Sample proposed tags CSV showing low, high and medium confidence rows, with CloudFormation-managed r


Step 3: Review

Add an  approved  column and sort by  confidence . Then check four things:
  • Values match the schema exactly. One  Dev  next to  dev  splits your cost reports.
  • No row with  managed_by  set is approved for API tagging.
  • The  source  supports the value. "Name contains orders" is fair evidence for  Application  and weak evidence for  Owner .
  • No personal data appears in any value.
Approve high-confidence rows, and medium rows only where the source convinces you. Send low-confidence rows and the "needs owner" list to the owning teams. It's slower, but your bill only carries tags someone checked. In my run I approved 46 rows and held back the 2 conflicts.

Step 4: Apply

Option A: the console. For a few hundred resources in one account, use Resource Explorer. Search, select up to 400 resources, choose Actions → Manage tags, add the tags and apply. It works across Regions. Leave CloudFormation stacks out of the selection.

alt text: Resource Explorer Manage tags dialog adding a CostCenter tag to several selected resources


Option B: the script. For more resources or more accounts, use the Resource Groups Tagging API. Here's the whole script:
"""Apply APPROVED tags from a CSV. Dry-run by default; never untags.
CSV columns: account_id,region,arn,key,value,source,confidence,managed_by,approved
Usage: python apply_tags.py approved_tags.csv [--role-name TagWriter] [--apply]
"""
import argparse, collections, csv, datetime, json, time, boto3
from botocore.config import Config

p = argparse.ArgumentParser()
p.add_argument("csv"); p.add_argument("--role-name"); p.add_argument("--apply", action="store_true")
p.add_argument("--log", default="tag_log.jsonl")
args = p.parse_args()
RETRY = Config(retries={"mode": "adaptive", "max_attempts": 10}) # backs off on ThrottledException (5 req/s)

# (account, region) -> arn -> {key: value}; skip unapproved and IaC-managed rows
plan = collections.defaultdict(lambda: collections.defaultdict(dict))
for r in csv.DictReader(open(args.csv, newline="")):
if r["approved"].strip().lower() == "yes" and not r["managed_by"].strip():
plan[(r["account_id"], r["region"])][r["arn"]][r["key"]] = r["value"]

def client(account, region):
s = boto3.Session()
if args.role_name:
c = s.client("sts").assume_role(RoleArn=f"arn:aws:iam::{account}:role/{args.role_name}",
RoleSessionName="apply-tags")["Credentials"]
s = boto3.Session(c["AccessKeyId"], c["SecretAccessKey"], c["SessionToken"])
return s.client("resourcegroupstaggingapi", region_name=region, config=RETRY)

def tags_of(api, arns): # GetResources: up to 100 ARNs; omits untagged resources and IAM roles
out = {}
for i in range(0, len(arns), 100):
for m in api.get_resources(ResourceARNList=arns[i:i + 100])["ResourceTagMappingList"]:
out[m["ResourceARN"]] = {t["Key"]: t["Value"] for t in m["Tags"]}
return out

records = []
for (account, region), arns in plan.items():
api = client(account, region)
before = tags_of(api, list(arns))
groups = collections.defaultdict(list) # resources with identical tag sets share a call
for arn, tags in arns.items():
groups[json.dumps(tags, sort_keys=True)].append(arn)
for tag_json, members in groups.items():
for i in range(0, len(members), 20): # TagResources: at most 20 ARNs per call
batch, tags = members[i:i + 20], json.loads(tag_json)
print(f"{'APPLY' if args.apply else 'DRY-RUN'} {account} {region} {len(batch)} ARNs <- {tags}")
failed = api.tag_resources(ResourceARNList=batch, Tags=tags)["FailedResourcesMap"] if args.apply else {}
if failed:
print(" FailedResourcesMap:", json.dumps(failed, indent=2))
records += [dict(account=account, region=region, arn=a, tags=tags, before=before.get(a, {}),
error=failed.get(a), api=api) for a in batch]

if args.apply:
time.sleep(5) # GetResources lags TagResources by a few seconds
with open(args.log, "a") as log:
for r in records:
api = r.pop("api")
r["after"] = tags_of(api, [r["arn"]]).get(r["arn"], {}) if args.apply else None
r.update(applied=args.apply, time=datetime.datetime.now(datetime.timezone.utc).isoformat())
log.write(json.dumps(r) + "\n")
It:
  • Reads only rows with  approved=yes  and skips any row with  managed_by  set.
  • Groups resources that get the same tags, and calls  TagResources  with up to 20 ARNs per call, the API's limit. With 21 ARNs the call fails with  Member must have length less than or equal to 20 .
  • Assumes  TagWriter  in each account when you pass  --role-name .
  • Runs as a dry run unless you pass  --apply , and logs before and after tags to a JSONL file.
  • Retries with backoff, because  TagResources  allows 5 requests per second, and prints  FailedResourcesMap , because one call can succeed while individual resources in it fail.
In my sandbox, the dry run planned 17 resources in 9 calls and skipped the 3 IaC-managed ones.  --apply  finished in 6 seconds with no failures, and a second run changed nothing. Resource Explorer showed the new tags after 6 to 21 seconds in the aggregator's Region and 32 to 47 seconds from the other Region, so allow a minute before you check.

Step 5: Terraform-managed resources

Don't tag Terraform-managed resources through the console or the API. To show why, I used the API to add  CostCenter  to a Terraform-managed queue and change its  Environment  to  prod , then ran  terraform plan :
# aws_sqs_queue.demo will be updated in-place
~ resource "aws_sqs_queue" "demo" {
~ tags = {
- "CostCenter" = "cc-123" -> null
- "Environment" = "prod" -> null
}
~ tags_all = {
- "CostCenter" = "cc-123" -> null
~ "Environment" = "prod" -> "dev"
# (1 unchanged element hidden)
}
}

Plan: 0 to add, 1 to change, 0 to destroy.
The next apply removes the extra tag and reverts the changed one. Fix it in the code instead. Add  default_tags  to the AWS provider, ideally in your AFT account customisations or shared provider config, so every resource gets the baseline tags:
provider "aws" {
region = "us-west-2"
default_tags {
tags = {
Environment = "dev"
ManagedBy = "terraform"
}
}
}
For tags that differ by resource, ask the agent to open a pull request against your Terraform code, using the rows it marked  managed_by=terraform . Terratag and yor can also add tags to existing Terraform code in bulk. Either way, the plan should show tag changes only.
CloudFormation behaves the same way. When I tagged a resource inside a stack through the API, the stack reported  DRIFTED . When I tagged the stack itself through the API, it ran a full stack update and pushed the tag to every resource in it. Tag stacks through CloudFormation.

Step 6: Lock it in

A backfill doesn't help if new resources keep arriving untagged. Put four controls in place:
Tag policies in AWS Organizations define the keys, allowed values and casing. Start in report-only mode, then enforce them for the resource types that matter:
{
"tags": {
"Environment": {
"tag_key": { "@@assign": "Environment" },
"tag_value": { "@@assign": ["dev", "test", "prod"] },
"enforced_for": { "@@assign": ["sqs:queue", "dynamodb:table", "sns:topic"] }
},
"Owner": {
"tag_key": { "@@assign": "Owner" }
},
"CostCenter": {
"tag_key": { "@@assign": "CostCenter" }
}
}
}
Required tag keys for IaC, launched in November 2025, also checks tag policies at deploy time, through the Terraform AWS provider's  tag_policy_compliance  setting, a CloudFormation Hook, or Pulumi. Start Terraform on  warning  and move to  error  once the warnings stop.
An SCP with  aws:RequestTag  blocks creating key resource types without the required tag. Test it in a sandbox OU first, because it will break any pipeline that doesn't tag on create.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyCreateWithoutEnvironmentTag",
"Effect": "Deny",
"Action": [
"sqs:CreateQueue",
"sns:CreateTopic",
"dynamodb:CreateTable",
"lambda:CreateFunction"
],
"Resource": "*",
"Condition": {
"Null": { "aws:RequestTag/Environment": "true" }
}
}
]
}
The AWS Config  required-tags  rule reports non-compliant resources. The  AWS-SetRequiredTags  automation doesn't work as remediation for this rule, so you'll need a custom Systems Manager document if you want auto-remediation.
Cost allocation tags need activating in the management (payer) account, for both account tags and resource tag keys. Activation takes up to 24 hours and doesn't apply to past months unless you request a backfill.
IAM Access Analyzer reported no findings on either policy document. I couldn't attach the tag policy or the SCP in a single sandbox account, so test both in a non-production OU before you roll them out.

Bonus: make the tags pay

Instance Scheduler on AWS starts and stops EC2 instances and RDS databases on a schedule set by a tag. Once your development resources carry  Schedule=office-hours , shutting them down outside working hours takes one deployment. It turns the tagging work into a saving you can see on the next bill.

Gotchas

  • Resource Explorer tag filters ignore case. Find resources with Resource Explorer, then verify exact keys with  GetResources .
  • Duplicate keys coexist. Adding  Environment  to a resource that already has  env  or  environment  keeps both. The script never removes tags, so clean up old keys in a separate, reviewed step.
  • IaC drift. If a resource is in Terraform state or a CloudFormation stack, tag it there.
  • SQS queues created by CloudFormation have no  aws:cloudformation:*  tags. Check stack resources, not just tags, to spot IaC-managed resources.
  • IAM roles.  TagResources  can tag them (the writer needs  iam:TagRole ), but  GetResources  never returns them and Resource Explorer doesn't show their tags. Check them with  aws iam list-role-tags .
  • Region matters. If you call  TagResources  in one Region with an ARN from another, it fails with  Region in the ARN ... does not match with the region in which TagResources API is invoked .
  • Delays. New resources took up to 3 minutes to appear in search, and  GetResources  returned new tags about 2 seconds after the write.
  • CloudTrail event history covers 90 days, so older resources have no recorded creator. That's what the "needs owner" list is for.
  • Tag propagation. Auto Scaling group tags reach instances only at launch, and instance tags don't copy to existing EBS volumes.
  • No personal data or secrets in tags. Tags appear in billing data, logs and many consoles.

Wrap-up

Here's the order: agree what tags are for and keep the schema small, tag accounts, let a read-only agent propose, approve what the evidence supports, apply one account at a time (Terraform through  default_tags  and pull requests), then lock it in and put the tags to work.
The agent does the matching. You keep the judgement and the write access.

Further reading

Any opinions in this article are my own and may not reflect the opinions of AWS.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article