我能否以编程方式找到所有未标记的资源?

Can I programmatically find all untagged resources?

AWS 网络控制台中的标签编辑器允许我搜索 "All resource types" 不存在特定标签的地方。例如,我可以列出缺少标签 "environment".

的所有内容

我想运行将此作为定期检查,以确保没有创建新的未标记资源。一些 Boto 代码(运行ning 作为 Lambda cron 作业)似乎很合适。但是,Boto 文档仅向我展示了如何查看特定资源类型(例如 EC2 实例)。

是否有任何API用于询问一般标签?还是我需要枚举每种资源类型?

标签一般没有API。您必须为每种服务类型执行此操作。这并不难。我有一个执行的 Lambda(通过 S3 PutObject / CloudTrail),它检查新创建的实例并在需要时标记它们。由于 CloudTrail 监控大部分 AWS 服务,因此很容易将其扩展到其他类型的 AWS 服务。但是,如果您要查找所有未标记的资源,则必须编写一个 Boto 脚本并查询每种服务类型的标签。

如果以后有人寻找同样的问题,就在这里发帖。

AWS 资源组提供这样的功能。您可以通过 https://console.aws.amazon.com/resource-groups/home 访问 AWS 控制台中的资源组。 我没有找到如何在 CLI 中使用 --tag-filters 和未标记的值,所以使用 jq 来过滤结果。

这是一个示例命令,用于获取没有环境标签的所有资源。

aws resourcegroupstaggingapi get-resources --tags-per-page 100 | jq '.ResourceTagMappingList[] | select(contains({Tags: [{Key: "environment"} ]}) | not)'

通过 resourcegroupstaggingapi 引用获取资源 - https://docs.aws.amazon.com/cli/latest/reference/resourcegroupstaggingapi/get-resources.html

有关资源组 API 的更多信息,请访问 https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetResources.html

根据 this write-up,您可以从控制台使用 AWS 资源组来查找标签值为空的资源。要查找具有标签键但没有标签值的资源,请选择(未标记)。

如果您正在寻找自动提醒,请考虑使用 AWS Config Rules and take a look at this related blog as well. In particular, there is a rule template called "required_tags" that checks for the presence of up to 5 tags. You can run more instances of the rule as needed, or modify the code. Find links that that and other rule templates here

我还发现 nice blog 通过在通过 CLI 调用服务 API 时使用过滤来帮助回答问题。

我还发现使用 AWS Config 的效果也很好。为特定 AWS 区域设置 AWS Config 后,您可以提交高级查询以查找缺失的标签,例如 EC2 资源上缺失标签的查询:

SELECT
  resourceId,
  resourceType,
  configuration.instanceType,
  configuration.placement.tenancy,
  configuration.imageId,
  tags,
  availabilityZone
WHERE
  resourceType = 'AWS::EC2::Instance'
  AND tags.key NOT LIKE 'owner'