Metadata-Version: 2.4
Name: driftwatch-cli
Version: 0.1.0
Summary: CLI tool that detects Terraform infrastructure drift against live AWS, explains it with AI, and guides remediation.
Author: Nitin Gupta
License: MIT
Project-URL: Homepage, https://github.com/hastagnitin/driftwatch
Project-URL: Repository, https://github.com/hastagnitin/driftwatch
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: boto3>=1.34.0
Requires-Dist: typer>=0.9.0
Requires-Dist: groq>=0.4.0
Requires-Dist: python-telegram-bot>=20.0
Requires-Dist: psycopg2-binary>=2.9.0
Requires-Dist: requests>=2.31.0
Requires-Dist: python-dotenv>=1.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: moto[all]>=5.0.0; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

# DriftWatch 🛡️

**DriftWatch** is a production-ready CLI tool and automation engine that detects Terraform infrastructure drift against live AWS environments, explains the security and reliability impact using AI, and safely guides remediation.

---

## 🚀 Key Features

- **Multi-Resource Drift Detection**: Continuously monitors and compares EC2 instances, S3 buckets, Security Groups, RDS databases, Lambda functions, and IAM roles against your Terraform state.
- **Data-Driven Severity Scoring**: Evaluates changes dynamically at the attribute level (e.g. security group open ports vs description updates) to classify drifts as `CRITICAL`, `HIGH`, `MEDIUM`, or `LOW`.
- **AI-Powered Risk Summaries**: Integrates with LLMs to provide plain-English security analysis and compliance impact assessments.
- **Deterministic IaC Remediation**: Recommends safe, template-generated `terraform import` and `terraform apply` commands rather than hallucinated AI outputs.
- **Guarded Auto-Remediation**: Pre-flight validation checks for EC2 (EBS verification, Spot skip, running state), RDS maintenance-window defaults, and explicit interactive confirmations.
- **Multi-Channel Alerting**: Instant notifications via Telegram, Slack, and Email.
- **CI/CD Quality Gate**: Built-in GitHub Actions integration to enforce zero-tolerance drift policies in pull requests.

---

## 🏛️ Architecture Overview

```
driftwatch/
├── drift_engine/              # Core drift detection & reconciliation engine
│   ├── aws_client.py         # Live AWS resource discovery (boto3)
│   ├── core.py               # Diff evaluation & data-driven severity engine
│   ├── database.py           # PostgreSQL scan history recorder
│   ├── explain.py            # AI risk summaries & deterministic IaC templates
│   ├── models.py             # Data models & attribute severity tables
│   ├── notifications.py      # Alert dispatcher (Telegram, Slack, Email)
│   ├── remediation.py        # Guarded auto-remediation handlers
│   └── tf_parser.py          # Terraform state JSON parser
├── driftwatch/               # CLI Entrypoint (Typer)
│   └── cli.py                # Command definitions: scan, explain, remediate
├── terraform/                # Example infrastructure and state configuration
├── kubernetes/               # Kubernetes CronJob deployment
└── tests/                    # Comprehensive unit tests with moto AWS mocks
```

---

## 📋 Prerequisites

- **Python**: `>= 3.10`
- **AWS Credentials**: Configured via environment variables, IAM roles, or AWS CLI credentials (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`).
- **Terraform State File**: Local JSON state or remote state (`terraform.tfstate`).
- **PostgreSQL** *(Optional)*: For persistent scan audit history.
- **Groq API Key** *(Optional)*: `GROQ_API_KEY` for AI risk explanations.

---

## 📦 Installation

### From Source (Local Development)
```bash
git clone https://github.com/hastagnitin/driftwatch.git
cd driftwatch
pip install -e .[dev]
```

---

## ⚙️ Configuration

Create a `.env` file in the root directory:

```env
AWS_DEFAULT_REGION=ap-south-1
TF_STATE_PATH=terraform/terraform.tfstate

# Optional: AI Risk Summaries
GROQ_API_KEY=your_groq_api_key

# Optional: Notifications
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
TELEGRAM_BOT_TOKEN=your_telegram_bot_token
TELEGRAM_CHAT_ID=your_telegram_chat_id

# Optional: PostgreSQL Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=driftwatch
DB_USER=postgres
DB_PASSWORD=your_db_password
```

---

## 💻 Usage & CLI Commands

### 1. Scan for Drift
Scan live AWS infrastructure against your Terraform state:
```bash
# Basic scan
driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate

# Enforce CI Gate (fails build if CRITICAL drift is found)
driftwatch scan --region ap-south-1 --fail-on CRITICAL
```

### 2. Explain Drift
Generate AI risk analysis and deterministic IaC fix recommendations:
```bash
driftwatch explain sg-0123456789abcdef0 --region ap-south-1
```

### 3. Remediate Drift
Safely remediate drifted resources back to IaC specifications:
```bash
# Dry run mode (default)
driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run

# Apply mode with interactive confirmation
driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
```

---

## ⚠️ Security & Safety Guidelines

> [!WARNING]
> **Auto-Remediation Safety**:
> - Automated drift remediation is intended for **Development** and **Staging** environments.
> - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and recommends template-generated `terraform apply` / `terraform import` workflows.
> - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to avoid unplanned reboots.

---

## 🧪 Testing

Run the test suite with test coverage:
```bash
pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
```

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
