生成非 Terraform 创建的资源列表的最佳方法

Best way to generate a list of non-Terraform created resources

几天来,我一直在研究一种生成非 Terraform 创建的资源列表的方法。目前我正在使用标记方法,但这意味着无法标记的 AWS 资源也应从 AWS Config 查询中排除。

标记部分也很麻烦,因为这必须手动完成。

  1. 有没有办法让 Terraform(或 Terragrunt)自动对资源使用通用标签?
  2. 有没有办法要求 Terraform 或任何其他工具创建状态文件中不可用的资源列表?

由于没有好的方法知道资源是否由 terraform 管理,我会尝试以下方法:

使用 terraformer 导入所有资源(并非所有资源都受 terraformer 支持,因此这不是一个完整的解决方案),在获得此列表后,只需减去由您管理的所有资源Terraform 从中声明。当 运行 terraform plan 你可以看到你的资源 ID。

如果您有所有 Terraform 托管资源的标签,您可以使用 terraformer

过滤它们
  1. Is there a way to tell Terraform (or Terragrunt) to automatically use general tags on resources?

不,这是不可能的。可以说,这将违背 Terraform 概念模型的声明,因此这不太可能成为 Terraform 的一个功能。

Terraform Enterprise 有策略执行,可用于强制用户提供特定标签,但我不认为它可以自动注入标签。

  1. Is there a way to ask Terraform or any other tool to create a list of resources that are not available in the state files?

没有。 Terraform 关心其状态文件中的资源。它不关心其他任何事情。


我个人认为您是从错误的角度来解决这个问题的。询问 Terraform“你 知道什么”如果可能的话会很方便(但事实并非如此)但是如果你查阅它的列表你会得到更好的答案 *是否知道资源是否属于 Terraform 的一部分并据此推断。

我不知道您正在使用的工具或您希望的工作流程,但您可以这样做:

  • 使用 terraform show -json 命令生成一个 JSON 文档,代表 Terraform 状态文件中所有已知的基础设施。

  • 使用工具jq解析JSON资源ID列表

  • 使用aws resourcegroupstaggingapi get-resources command to generate a list of all known resources, or perhaps even a tool like aws-list-all

  • 遍历 'all resources' 列表中的每个条目;对于每一个,遍历 'Terraform-managed' 列表中的每个条目;如果没有匹配项,将资源 ID 添加到 'not-managed-by-Terraform' 资源列表

我同意 Chuppa Chump 的回答,如果不是很明显,我会添加,以确保所有 Terraform 创建的资源都有一个标签,表明它是由 Terraform 创建的。例如,CreatedBy =“Terraform”或 Automation =“Terraform”。然后任何没有 Automation 或 CreatedBy 标签的资源都不是由 terraform 创建的。

对于仍然绊倒这个的人。社区似乎创建了一个名为 Driftctl 的工具,可以根据您的 Terraform 状态检查环境。