如何在Lambda中通过资源ID/ARN获取AWS资源(EC2、DynamoDB等)的指定标签?
在Lambda中查询AWS资源标签的实现方法
一、配置Lambda执行角色权限
首先要给Lambda的执行角色添加必要的IAM权限,核心权限如下:
tag:GetResources:用于通过统一API跨服务查询资源标签resource-groups:GetGroupResources:如果需要从已创建的资源组获取资源列表- (可选)若单独调用各服务API,需添加对应权限,比如EC2的
ec2:DescribeTags、DynamoDB的dynamodb:ListTagsOfResource
权限策略示例(可直接附加到Lambda角色):
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "tag:GetResources", "resource-groups:GetGroupResources" ], "Resource": "*" } ] }
二、两种实现方式
方式1:使用统一的Resource Groups Tagging API(推荐)
这个API支持跨所有标签兼容的AWS服务查询标签,无需针对EC2、DynamoDB编写不同逻辑,效率更高。
场景A:从资源组获取资源并查询标签
示例Python代码:
import boto3 def lambda_handler(event, context): # 初始化客户端 resource_groups = boto3.client('resource-groups') tagging_client = boto3.client('resourcegroupstaggingapi') # 替换为你的资源组名称 group_name = 'your-resource-group-name' # 获取资源组内的所有资源ARN resources_response = resource_groups.get_group_resources(GroupName=group_name) resource_arns = [item['Identifier']['Arn'] for item in resources_response['ResourceIdentifiers']] # 批量查询资源标签 tags_response = tagging_client.get_resources(ResourceARNList=resource_arns) # 整理结果:资源ARN对应标签键值对 resource_tags = {} for resource in tags_response['ResourceTagMappingList']: arn = resource['ResourceARN'] tags = {tag['Key']: tag['Value'] for tag in resource['Tags']} resource_tags[arn] = tags return resource_tags
场景B:直接通过资源ID/ARN查询标签
如果已知目标资源的ARN或ID,可直接传入查询:
import boto3 def lambda_handler(event, context): tagging_client = boto3.client('resourcegroupstaggingapi') # 替换为你要查询的资源ARN列表 target_arns = [ 'arn:aws:ec2:us-east-1:123456789012:instance/i-0123456789abcdef0', 'arn:aws:dynamodb:us-east-1:123456789012:table/MyDynamoDBTable' ] response = tagging_client.get_resources(ResourceARNList=target_arns) # 整理标签结果 result = {} for item in response['ResourceTagMappingList']: result[item['ResourceARN']] = {tag['Key']: tag['Value'] for tag in item['Tags']} return result
方式2:调用各服务专属API
若仅针对特定服务查询,可直接调用对应服务的API:
示例:查询EC2实例标签
import boto3 def lambda_handler(event, context): ec2 = boto3.client('ec2') instance_id = 'i-0123456789abcdef0' response = ec2.describe_tags(Filters=[{'Name': 'resource-id', 'Values': [instance_id]}]) tags = {tag['Key']: tag['Value'] for tag in response['Tags']} return tags
示例:查询DynamoDB表标签
import boto3 def lambda_handler(event, context): dynamodb = boto3.client('dynamodb') table_arn = 'arn:aws:dynamodb:us-east-1:123456789012:table/MyDynamoDBTable' response = dynamodb.list_tags_of_resource(ResourceArn=table_arn) tags = {tag['Key']: tag['Value'] for tag in response['Tags']} return tags
三、注意事项
- 分页处理:若资源组内资源较多,
get_group_resources和get_resources会返回NextToken,需循环调用直到获取所有资源 - ARN格式校验:确保传入的资源ARN格式正确,不同服务的ARN结构存在差异
- 权限最小化:若无需跨全服务查询,可限制
tag:GetResources的资源范围,或仅添加特定服务的标签权限
内容的提问来源于stack exchange,提问作者hugh_R
相关产品推荐
相关产品推荐

