如何使用 boto3 通过 ID(而不是 ARN)获取资源标签?

问题描述 投票:0回答:1

我尝试使用 boto3 lib 从 AWS CostExplorer 收集统计信息。 我使用了方法 get_cost_and_usage_with_resources (请参阅详细信息:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ce/client/get_cost_and_usage_with_resources.html),它返回带有资源的响应(ID或 ARN),它们的使用情况和成本。

我想使用与这些资源相关的标签来映射这些数据,但问题是,如果我有资源 ARN,我可以映射它们。在这种情况下,我使用方法 get_resources (请参阅详细信息:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/resourcegroupstaggingapi/client/get_resources.html)。此方法仅接受 ARN 列表,而不接受 ID。

如果我只有资源 ID(例如 EC2 卷 vol-0053852a4f079axxx ),我无法获取资源标签。

所以问题是,如果我只有资源 ID 并且不想为每个服务单独创建 boto3 客户端,如何获取任何 AWS 资源的标签?

我尝试使用方法 get_resources (请参阅详细信息:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/resourcegroupstaggingapi/client/get_resources.html),但它返回错误因为它只接受资源 ARN

代码如下:

import boto3

tag_client = boto3.client('resourcegroupstaggingapi')

def get_resource_tags(resource_arn):
response = tag_client.get_resources(
ResourceARNList=[resource_arn]
)
print(response)

get_resource_tags("vol-0e6abc422806b0xxx")

错误如下:

botocore.errorfactory.InvalidParameterException: An error occurred (InvalidParameterException) when calling the GetResources operation: vol-0e6abc422806b0xxx is not a valid AmazonResourceName (ARN)
python-3.x amazon-web-services boto3 aws-cost-explorer
1个回答
0
投票

resourcegroupstaggingapi
仅接受资源 arn,因此如果您确实想将其与 ec2 id 一起使用,那么您应该根据 id 创建一个 arn。请参阅此处的文档。 AWS 为几乎所有资源提供 arn 结构。

© www.soinside.com 2019 - 2024. All rights reserved.