tfdrift 新增 remediate 子命令,可自动扫描所有 workspace 的基础设施漂移并生成修复 .tf 文件,目前支持 Slack/Teams/OpsGenie 告警。
如果你长期使用 Terraform,一定有过这种体验:跑一下 terraform plan,突然冒出来 12 个意料之外的变更。有人直接在控制台改了实例类型,安全组规则被人手动加了一条,某个 tag 被删掉了。基础设施发生了漂移——现在你得搞清楚哪里变了、为什么变、以及如何让它恢复正常。
检测漂移是一回事,真正动手修复才是工程师浪费时间的地方。
这就是我构建 tfdrift remediate 要解决的问题。
tfdrift(https://github.com/sudarshan8417/tfdrift)是一个开源 CLI 工具,用于持续检测 Terraform 和 OpenTofu 的漂移。它在你的所有 workspace 上运行 terraform plan,按严重程度(critical / high / medium / low)对漂移进行分类,然后通过 Slack、Teams 或 OpsGenie 发送告警。
0.5.3 版本引入了一个新命令——tfdrift remediate——它接收检测到的漂移,利用 AI 生成一个可以直接审查的 .tf 修复文件。
检测到漂移后,典型的工作流程是:
terraform plan 的输出.tf 文件,使其匹配期望状态1-2 个资源时这还好。当涉及 10+ 个资源、跨多个 workspace,尤其是处理 aws_security_group、aws_iam_role_policy、azurerm_virtual_network 这类复杂资源类型时,这就变成了一个缓慢且容易出错的过程。
tfdrift remediate --path ./infra
drift-remediation.tf 文件供你审查和应用交互式提示界面如下:
Found 3 drifted resource(s):
aws_instance.web 🔴 high — 2 attribute change(s)
aws_s3_bucket.logs 🟡 medium — 1 attribute change(s)
aws_security_group.app 🔴 high — 3 attribute change(s)
What would you like to remediate? A — All resources S — Select specific resources (comma-separated numbers) Q — Quit
选择 S 并输入 1,3 可以只修复高严重程度的资源。或者直接按 A 为所有资源生成修复方案。
AI 会收到完整的漂移上下文——资源类型、需要执行的操作,以及每个变更属性的期望值与实际值。它输出有效的 HCL,并在行内注释中解释每项修正:
resource "aws_instance" "web" {
instance_type = "t3.medium" # corrected: actual was t3.large
# ... other attributes unchanged
}
resource "aws_security_group" "app" {
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"]
}
# ... other attributes unchanged
}
审查后做任何必要的调整,然后应用:
terraform apply drift-remediation.tf
tfdrift remediate 会根据你的环境变量自动检测使用哪个 AI provider:
ANTHROPIC_API_KEY → 使用 Claude(首选)OPENAI_API_KEY → 使用 GPT-4o(备选)也可以强制指定某个 provider:
tfdrift remediate --provider openai --path ./infra
pip install 'tfdrift[ai]'
export ANTHROPIC_API_KEY=sk-ant-... tfdrift remediate --path ./infra
export OPENAI_API_KEY=sk-... tfdrift remediate --path ./infra
tfdrift remediate --all
tfdrift remediate --output my-fixes.tf
tfdrift remediate --binary tofu
terraform apply 直接搞定?tfdrift remediate 不同于 tfdrift scan --auto-fix(后者直接运行 terraform apply)。AI 修复命令生成的是一个文件,先让你审查——AI 会解释它在修正什么、为什么这么改,然后你确认没问题后再应用。
在生产环境中这一点很重要。你需要一个人在上线之前审核这个修复方案。
其他功能亮点:
--min-severity high 只修复 critical 和 high 级别的漂移)tfdrift 是开源软件(Apache 2.0)。如果你正在使用它或有反馈意见,欢迎在 GitHub 上提 issue 或点个 star(https://github.com/sudarshan8417/tfdrift)。