如何使用Boto3查找AWS中从未被标记的资源?
使用Boto3查找AWS中未标记的资源
Resource Groups Tagging API的get_resources方法默认仅返回带有标签的资源,无法直接用它筛选无标签资源。下面提供两种可行的实现思路:
方法一:按服务枚举资源并逐个检查标签
针对特定AWS服务,调用对应的资源列举API,再逐一判断资源是否未设置标签。
示例:查找无标签的EC2实例
import boto3 def find_untagged_ec2_instances(): ec2_client = boto3.client('ec2') response = ec2_client.describe_instances() untagged_instance_ids = [] for reservation in response['Reservations']: for instance in reservation['Instances']: # 检查实例是否无标签 if 'Tags' not in instance or len(instance['Tags']) == 0: untagged_instance_ids.append(instance['InstanceId']) return untagged_instance_ids # 执行并输出结果 print("无标签EC2实例ID列表:", find_untagged_ec2_instances())
扩展到其他服务
不同服务的检查逻辑类似,只需替换对应的API:
- S3:用
list_buckets列举所有存储桶,再调用get_bucket_tagging,若抛出NoSuchTagSet异常则说明该桶无标签 - RDS:调用
describe_db_instances,检查返回结果中的TagList字段是否为空
方法二:对比全量资源与带标签资源
先通过Tagging API获取所有带标签的资源,再通过各服务API获取全量资源,两者取差集得到无标签资源。
import boto3 from collections import defaultdict def get_all_tagged_resources(): tag_client = boto3.client('resourcegroupstaggingapi') tagged_resources = defaultdict(list) # 分页处理避免结果过大 paginator = tag_client.get_paginator('get_resources') for page in paginator.paginate(): for resource in page['ResourceTagMappingList']: resource_type = resource['ResourceType'] resource_arn = resource['ResourceARN'] tagged_resources[resource_type].append(resource_arn) return tagged_resources def find_untagged_ec2_instances(): tagged_resources = get_all_tagged_resources() ec2_client = boto3.client('ec2') # 获取所有EC2实例ID all_instance_ids = [ instance['InstanceId'] for reservation in ec2_client.describe_instances()['Reservations'] for instance in reservation['Instances'] ] # 转换带标签实例的ARN为实例ID account_id = boto3.client('sts').get_caller_identity()['Account'] region = ec2_client.meta.region_name tagged_ec2_arns = tagged_resources.get('ec2:instance', []) tagged_instance_ids = [arn.split('/')[-1] for arn in tagged_ec2_arns] # 计算差集得到无标签实例 untagged_instance_ids = list(set(all_instance_ids) - set(tagged_instance_ids)) return untagged_instance_ids print("无标签EC2实例ID列表:", find_untagged_ec2_instances())
注意事项
- 确保IAM角色拥有对应服务的
List类权限,以及Resource Groups Tagging API的GetResources权限 - 资源量较大时,建议使用分页、批量处理来提升效率
- 不同服务的ARN格式存在差异,转换时需对应调整规则
内容的提问来源于stack exchange,提问作者Tharindu Kavinda
相关产品推荐
相关产品推荐

