sudarshan8417/tfdrift
GitHub: sudarshan8417/tfdrift
一款免费的 Python CLI 工具,用于持续检测 Terraform 管理的基础设施配置漂移,支持严重性分级、自动修复和团队告警,填补了 driftctl 归档后的开源工具空白。
Stars: 1 | Forks: 0
# tfdrift
**持续的 Terraform 漂移检测、报告及自动修复。**
[](https://www.python.org/downloads/
[](https://pypi.org/project/tfdrift/)
[](LICENSE)
[](https://github.com/sudarshan8417/tfdrift/actions)

`tfdrift` 是一个 Python CLI 工具,用于监控由 Terraform 管理的基础设施中的漂移 —— 即在 Terraform 工作流之外进行的更改(控制台点击、脚本、其他工具)。它会扫描你的 Terraform 工作区,检测状态与实际情况之间的差异,生成结构化报告,并可选择自动修复或通知你的团队。
**为什么选择 tfdrift?** 最受欢迎的开源漂移检测工具([driftctl](https://github.com/snyk/driftctl))自 2023 年中以来一直处于维护模式。像 Terraform Enterprise 这样的企业级解决方案每年的费用高达 1.5 万美元以上。`tfdrift` 填补了这一空白:一个免费、现代且积极维护的 CLI 工具,专注于把一件事做到极致。
## 功能
- **多工作区扫描** —— 递归发现目录树中的所有 Terraform 工作区
- **结构化漂移报告** —— JSON、Markdown 或人类可读的表格输出
- **严重性分类** —— 根据资源类型和属性,按风险级别(严重/高/中/低)对漂移进行分类
- **Slack 与 webhook 通知** —— 在检测到漂移的瞬间收到警报
- **自动修复** —— 可选择运行 `terraform apply` 来修复漂移(带有安全保障)
- **对 CI/CD 友好** —— 开箱即用的退出码、JSON 输出和 GitHub Actions 集成
- **监控模式** —— 按计划持续监控漂移情况
- **忽略规则** —— 使用 `.tfdriftignore` 过滤掉已知或预期的漂移
## 快速开始
### 安装
```
pip install tfdrift
```
### 扫描漂移
```
# 扫描当前目录的所有 Terraform 工作区
tfdrift scan
# 扫描特定目录
tfdrift scan --path /path/to/terraform
# 输出为 JSON
tfdrift scan --format json
# 输出为 Markdown 报告
tfdrift scan --format markdown --output drift-report.md
```
### 本地尝试(无需云凭证)
使用 Terraform 的 `null` provider 和本地 backend 来模拟漂移:
```
# 1. 创建工作区并应用初始状态
mkdir -p /tmp/tfdrift-demo && cat > /tmp/tfdrift-demo/main.tf <<'EOF'
terraform {
required_providers {
null = { source = "hashicorp/null", version = "~> 3.0" }
}
backend "local" {}
}
resource "null_resource" "server" {
triggers = { instance_type = "t3.micro", region = "us-east-1" }
}
resource "null_resource" "db" {
triggers = { engine = "postgres", version = "14" }
}
EOF
cd /tmp/tfdrift-demo && terraform init && terraform apply -auto-approve
# 2. 模拟漂移 — 更改配置而不更新状态
sed -i 's/t3.micro/t3.large/; s/us-east-1/us-west-2/; s/version = "14"/version = "15"/' main.tf
# 3. 运行 tfdrift
tfdrift scan --path /tmp/tfdrift-demo
```
预期输出:
```
⚠️ Drift detected: 2 resource(s) across 1/1 workspace(s)
🟡 medium: 2
📂 /tmp/tfdrift-demo (2 drifted, 0.3s)
┏━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┓
┃ Severity ┃ Resource ┃ Action ┃ Changed attributes ┃
┡━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━┩
│ MEDIUM │ null_resource.db │ replace │ id, triggers │
│ MEDIUM │ null_resource.server │ replace │ id, triggers │
└──────────┴───────────────────────┴─────────┴────────────────────┘
```
### 监控模式(持续监控)
```
# 每 30 分钟检查一次,发生漂移时通知 Slack
tfdrift watch --interval 30m --slack-webhook https://hooks.slack.com/services/XXX
```
### 自动修复
```
# 自动修复 dev 中的漂移(出于安全考虑,需要 --confirm)
tfdrift scan --auto-fix --confirm --env dev
# Dry run — 显示将要修复的内容
tfdrift scan --auto-fix --dry-run
```
## 配置
在你的项目根目录创建一个 `.tfdrift.yml`:
```
# .tfdrift.yml
scan:
paths:
- ./infrastructure
- ./modules
exclude:
- "**/test/**"
- "**/.terraform/**"
# Auto-detect .tfvars files in each workspace (default: true)
auto_detect_var_files: true
# Or specify explicit var files
var_files:
- envs/dev.tfvars
# Or pass variables directly
vars:
environment: production
region: us-east-1
severity:
critical:
- aws_security_group.*.ingress
- aws_iam_policy.*.policy
- aws_s3_bucket.*.acl
high:
- aws_instance.*.instance_type
- aws_rds_instance.*.engine_version
notifications:
slack:
webhook_url: ${SLACK_WEBHOOK_URL}
channel: "#infra-alerts"
min_severity: high
webhook:
url: ${WEBHOOK_URL}
method: POST
remediation:
auto_fix: false
allowed_environments:
- dev
- staging
require_approval: true
max_changes: 5 # safety limit
ignore:
# Ignore expected drift
- resource: aws_autoscaling_group.*
attribute: desired_capacity
- resource: aws_ecs_service.*
attribute: desired_count
```
## 忽略规则
创建一个 `.tfdriftignore` 文件以跳过已知的漂移:
```
# Autoscaling 变更是预期的
aws_autoscaling_group.*.desired_capacity
aws_ecs_service.*.desired_count
# 标签由外部系统管理
*.tags.LastModified
*.tags.UpdatedBy
```
## CI/CD 集成
### GitHub Actions
```
# .github/workflows/drift-check.yml
name: Terraform Drift Check
on:
schedule:
- cron: '0 */6 * * *' # Every 6 hours
workflow_dispatch:
jobs:
drift-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: pip install tfdrift
- run: tfdrift scan --format json --output drift-report.json
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- uses: actions/upload-artifact@v4
if: failure()
with:
name: drift-report
path: drift-report.json
```
### GitLab CI
```
drift-check:
image: python:3.11
before_script:
- pip install tfdrift
- apt-get update && apt-get install -y terraform
script:
- tfdrift scan --format json --output drift-report.json
rules:
- if: $CI_PIPELINE_SOURCE == "schedule"
artifacts:
paths:
- drift-report.json
when: on_failure
```
## 退出码
| 代码 | 含义 |
|------|---------|
| 0 | 未检测到漂移 |
| 1 | 检测到漂移 |
| 2 | 扫描期间发生错误 |
| 3 | 检测到漂移并已自动修复 |
## 架构
```
tfdrift/
├── commands/ # CLI command handlers (scan, watch, init)
├── detectors/ # Drift detection engine (terraform plan parser)
├── reporters/ # Output formatters (JSON, Markdown, table, Slack)
├── remediators/ # Auto-fix logic with safety guards
├── config.py # Configuration loader (.tfdrift.yml)
├── models.py # Data models (DriftResult, Resource, etc.)
├── severity.py # Severity classification engine
└── cli.py # CLI entry point (Click)
```
## 与替代方案对比
| 特性 | tfdrift | driftctl (已归档) | terraform plan | Terraform Enterprise |
|---------|---------|-------------------|----------------|---------------------|
| 积极维护 | ✅ | ❌ (自 2023 年起) | ✅ | ✅ |
| 多工作区扫描 | ✅ | ❌ | ❌ | ✅ |
| 严重性分类 | ✅ | ❌ | ❌ | ❌ |
| 自动修复 | ✅ | ❌ | ❌ | ✅ |
| Slack/webhook 警报 | ✅ | ✅ | ❌ | ✅ |
| 监控模式 | ✅ | ❌ | ❌ | ✅ |
| 忽略规则 | ✅ | ✅ | ❌ | ❌ |
| 费用 | 免费 | 免费 | 免费 | $15K+/yr |
| 语言 | Python | Go | Go (HCL) | 专有 |
## 贡献
欢迎贡献!请参阅 [CONTRIBUTING.md](CONTRIBUTING.md) 获取指南。
```
# 开发设置
git clone https://github.com/sudarshan8417/tfdrift.git
cd tfdrift
python -m venv venv
source venv/bin/activate
pip install -e ".[dev]"
pytest
```
## 许可证
Apache License 2.0 —— 详情请参阅 [LICENSE](LICENSE)。
## 致谢
灵感来源于 [driftctl](https://github.com/snyk/driftctl) 以及 Terraform 社区对维护开源漂移检测工具的需求。
标签:driftctl替代, EC2, ECS, GitHub Actions, IaC, Python, Slack通知, Terraform, 严重性分类, 工作区扫描, 开源, 持续监控, 无后门, 漂移检测, 漏洞利用检测, 状态管理, 自动修复, 自动笔记, 逆向工具