driftwatch-cli 3.0.1__tar.gz → 3.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. driftwatch_cli-3.0.3/PKG-INFO +278 -0
  2. driftwatch_cli-3.0.3/README.md +237 -0
  3. driftwatch_cli-3.0.3/drift_engine/__init__.py +17 -0
  4. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/drift_engine/aws_client.py +92 -53
  5. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/drift_engine/core.py +84 -33
  6. driftwatch_cli-3.0.3/drift_engine/database.py +127 -0
  7. driftwatch_cli-3.0.3/drift_engine/explain.py +112 -0
  8. driftwatch_cli-3.0.3/drift_engine/models.py +65 -0
  9. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/drift_engine/notifications.py +46 -43
  10. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/drift_engine/remediation.py +137 -74
  11. driftwatch_cli-3.0.3/drift_engine/tf_parser.py +88 -0
  12. driftwatch_cli-3.0.3/driftwatch/__init__.py +8 -0
  13. driftwatch_cli-3.0.3/driftwatch/cli.py +386 -0
  14. driftwatch_cli-3.0.3/driftwatch_cli.egg-info/PKG-INFO +278 -0
  15. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/driftwatch_cli.egg-info/SOURCES.txt +6 -1
  16. driftwatch_cli-3.0.3/driftwatch_cli.egg-info/requires.txt +18 -0
  17. driftwatch_cli-3.0.3/pyproject.toml +73 -0
  18. driftwatch_cli-3.0.3/tests/test_aws_client.py +164 -0
  19. driftwatch_cli-3.0.3/tests/test_cli.py +764 -0
  20. driftwatch_cli-3.0.3/tests/test_diff_engine.py +359 -0
  21. driftwatch_cli-3.0.3/tests/test_explain_notifications.py +217 -0
  22. driftwatch_cli-3.0.3/tests/test_remediation.py +385 -0
  23. driftwatch_cli-3.0.1/PKG-INFO +0 -17
  24. driftwatch_cli-3.0.1/drift_engine/__init__.py +0 -0
  25. driftwatch_cli-3.0.1/drift_engine/database.py +0 -54
  26. driftwatch_cli-3.0.1/drift_engine/explain.py +0 -47
  27. driftwatch_cli-3.0.1/drift_engine/models.py +0 -42
  28. driftwatch_cli-3.0.1/drift_engine/tf_parser.py +0 -67
  29. driftwatch_cli-3.0.1/driftwatch/__init__.py +0 -0
  30. driftwatch_cli-3.0.1/driftwatch/cli.py +0 -174
  31. driftwatch_cli-3.0.1/driftwatch_cli.egg-info/PKG-INFO +0 -17
  32. driftwatch_cli-3.0.1/driftwatch_cli.egg-info/requires.txt +0 -7
  33. driftwatch_cli-3.0.1/pyproject.toml +0 -31
  34. driftwatch_cli-3.0.1/tests/test_diff_engine.py +0 -39
  35. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/LICENSE +0 -0
  36. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/driftwatch_cli.egg-info/dependency_links.txt +0 -0
  37. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/driftwatch_cli.egg-info/entry_points.txt +0 -0
  38. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/driftwatch_cli.egg-info/top_level.txt +0 -0
  39. {driftwatch_cli-3.0.1 → driftwatch_cli-3.0.3}/setup.cfg +0 -0
@@ -0,0 +1,278 @@
1
+ Metadata-Version: 2.4
2
+ Name: driftwatch-cli
3
+ Version: 3.0.3
4
+ Summary: CLI tool that detects Terraform infrastructure drift against live AWS, explains it with AI, and guides remediation.
5
+ Author: Nitin Gupta
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/hastagnitin/driftwatch
8
+ Project-URL: Repository, https://github.com/hastagnitin/driftwatch
9
+ Keywords: terraform,aws,drift-detection,iac,devops,cloud-security,remediation
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: System Administrators
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: System :: Systems Administration
20
+ Classifier: Topic :: Security
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: boto3>=1.34.0
25
+ Requires-Dist: typer>=0.9.0
26
+ Requires-Dist: requests>=2.31.0
27
+ Requires-Dist: python-dotenv>=1.0.0
28
+ Provides-Extra: postgres
29
+ Requires-Dist: psycopg2-binary>=2.9.0; extra == "postgres"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
32
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
33
+ Requires-Dist: moto[all]>=5.0.0; extra == "dev"
34
+ Requires-Dist: build; extra == "dev"
35
+ Requires-Dist: twine; extra == "dev"
36
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
37
+ Requires-Dist: bandit>=1.7.0; extra == "dev"
38
+ Requires-Dist: mypy>=1.5.0; extra == "dev"
39
+ Requires-Dist: pip-audit>=2.6.0; extra == "dev"
40
+ Dynamic: license-file
41
+
42
+ # DriftWatch 🛡️
43
+
44
+ **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.
45
+
46
+ ---
47
+
48
+ ## 🚀 Key Features
49
+
50
+ - **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.
51
+ - **Data-Driven Severity Scoring**: Evaluates changes dynamically at the attribute level (e.g., security group open ingress ports vs. description updates) to classify drifts as `CRITICAL`, `HIGH`, `MEDIUM`, or `LOW`.
52
+ - **AI-Powered Risk Summaries**: Integrates with LLMs (Groq API) via lightweight direct HTTP requests to provide concise security analysis and compliance impact assessments.
53
+ - **Deterministic IaC Remediation**: Recommends safe, template-generated `terraform import` and `terraform apply` commands rather than hallucinated AI scripts.
54
+ - **Guarded Auto-Remediation**: Pre-flight validation checks for EC2 (EBS verification, Spot skip, running state), RDS maintenance-window defaults, and explicit interactive confirmations with `--yes` / `--force` automation overrides for CI/CD.
55
+ - **Batch Remediation & Scan Caching**: Remediate all drifted resources at once (`--all`), and pass scan outputs (`--from-scan`) to `explain` and `remediate` to avoid redundant AWS API sweeps.
56
+ - **Machine-Readable Outputs**: Export full scan reports in structured JSON format (`--json` or `--output json`).
57
+ - **Multi-Channel Alerting**: Instant notifications via Telegram, Slack, and Email.
58
+ - **Strict CI/CD Quality Gate**: Built-in gate enforcement (`--fail-on`) that halts pipelines with non-zero exit codes on threshold breaches, missing state, corrupted state, or AWS authentication failures.
59
+
60
+ ---
61
+
62
+ ## 🏛️ Architecture Overview
63
+
64
+ ```
65
+ driftwatch/
66
+ ├── drift_engine/ # Core drift detection & reconciliation engine
67
+ │ ├── __init__.py # Core exports (detect_drift, get_severity, models)
68
+ │ ├── aws_client.py # Live AWS discovery & Cost Explorer lookup (boto3)
69
+ │ ├── core.py # Diff evaluation & severity engine
70
+ │ ├── database.py # PostgreSQL scan history recorder (optional)
71
+ │ ├── explain.py # AI risk summaries & deterministic IaC templates
72
+ │ ├── models.py # Data models & attribute severity tables
73
+ │ ├── notifications.py # Alert dispatcher (Telegram, Slack, Email)
74
+ │ ├── remediation.py # Guarded auto-remediation handlers
75
+ │ └── tf_parser.py # Terraform state JSON parser
76
+ ├── driftwatch/ # CLI Entrypoint (Typer)
77
+ │ ├── __init__.py # Package version & engine alias (driftwatch.engine)
78
+ │ └── cli.py # Commands: scan, explain, remediate
79
+ ├── terraform/ # Example infrastructure and state configuration
80
+ ├── kubernetes/ # Kubernetes CronJob deployment
81
+ └── tests/ # Comprehensive unit tests with moto AWS mocks
82
+ ```
83
+
84
+ ---
85
+
86
+ ## 📋 Prerequisites
87
+
88
+ - **Python**: `>= 3.10`
89
+ - **AWS Credentials**: Configured via environment variables, IAM roles, or AWS CLI profiles (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`, or `--profile`).
90
+ - **Terraform State File**: Local JSON state or remote state (`terraform.tfstate`).
91
+ - **PostgreSQL** *(Optional)*: For persistent scan audit history.
92
+ - **Groq API Key** *(Optional)*: `GROQ_API_KEY` for AI risk explanations.
93
+
94
+ ---
95
+
96
+ ## 📦 Installation
97
+
98
+ ### From PyPI (Recommended)
99
+ ```bash
100
+ pip install driftwatch-cli
101
+
102
+ # With PostgreSQL support for persistent audit history
103
+ pip install "driftwatch-cli[postgres]"
104
+ ```
105
+
106
+ ### From Source (Local Development)
107
+ ```bash
108
+ git clone https://github.com/hastagnitin/driftwatch.git
109
+ cd driftwatch
110
+ pip install -e .[dev]
111
+ ```
112
+
113
+ ---
114
+
115
+ ## ⚙️ Configuration
116
+
117
+ Create a `.env` file in the root directory:
118
+
119
+ ```env
120
+ AWS_DEFAULT_REGION=ap-south-1
121
+ TF_STATE_PATH=terraform/terraform.tfstate
122
+
123
+ # Optional: AWS Named Profile
124
+ # AWS_PROFILE=prod-profile
125
+
126
+ # Optional: AI Risk Summaries
127
+ GROQ_API_KEY=your_groq_api_key
128
+
129
+ # Optional: Notifications
130
+ SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
131
+ TELEGRAM_BOT_TOKEN=your_telegram_bot_token
132
+ TELEGRAM_CHAT_ID=your_telegram_chat_id
133
+
134
+ # Optional: PostgreSQL Database
135
+ DB_HOST=localhost
136
+ DB_PORT=5432
137
+ DB_NAME=driftwatch
138
+ DB_USER=postgres
139
+ DB_PASSWORD=your_db_password
140
+ ```
141
+
142
+ ---
143
+
144
+ ## 💻 Usage & CLI Commands
145
+
146
+ Check CLI version and help:
147
+ ```bash
148
+ driftwatch --version # or: driftwatch -v
149
+ driftwatch --help # or: driftwatch -h
150
+ ```
151
+
152
+ ### 1. Scan for Drift (`driftwatch scan`)
153
+ Scan live AWS infrastructure against your Terraform state:
154
+
155
+ ```bash
156
+ # Standard scan
157
+ driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate
158
+
159
+ # Using a named AWS profile
160
+ driftwatch scan --region us-east-1 --profile staging-admin
161
+
162
+ # CI/CD Drift Gate (fails build with exit code 1 if CRITICAL drift is detected)
163
+ driftwatch scan --region ap-south-1 --fail-on CRITICAL
164
+
165
+ # Output as structured JSON (for dashboards or piped automation)
166
+ driftwatch scan --region ap-south-1 --output json > scan_results.json
167
+ # Or use shorthand:
168
+ driftwatch scan --region ap-south-1 --json > scan_results.json
169
+ ```
170
+
171
+ **Options for `driftwatch scan`:**
172
+ - `--state`: Path to Terraform state file (default: `terraform/terraform.tfstate`).
173
+ - `--region`: Target AWS region (or defaults to `AWS_DEFAULT_REGION`).
174
+ - `--profile`: Named AWS CLI profile to use for credentials.
175
+ - `--fail-on`: Severity threshold to trigger non-zero exit code (`LOW`, `MEDIUM`, `HIGH`, `CRITICAL`). Case-insensitive.
176
+ - `--output`, `-o`: Output format: `text` (default) or `json`.
177
+ - `--json`: Shorthand flag for `--output json`.
178
+
179
+ > [!NOTE]
180
+ > **CI Gate Reliability**: If the Terraform state file is missing or corrupted, or if live AWS resource fetching fails (e.g. invalid credentials or expired sessions), `driftwatch scan` immediately aborts with a non-zero exit code (`1`), preventing false-green builds in your CI/CD pipeline.
181
+
182
+ ---
183
+
184
+ ### 2. Explain Drift (`driftwatch explain`)
185
+ Generate AI risk analysis and deterministic IaC fix recommendations for a drifted resource:
186
+
187
+ ```bash
188
+ # Live query (fetches live AWS state for resource)
189
+ driftwatch explain sg-0123456789abcdef0 --region ap-south-1
190
+
191
+ # Zero-sweep query from previous scan file (instant, 0 AWS API calls)
192
+ driftwatch explain sg-0123456789abcdef0 --from-scan scan_results.json
193
+ ```
194
+
195
+ **Options for `driftwatch explain`:**
196
+ - `RESOURCE_ID`: ID of the resource to explain (e.g. `sg-xxx`, `i-xxx`).
197
+ - `--state`: Path to Terraform state file.
198
+ - `--region`: Target AWS region.
199
+ - `--profile`: Named AWS CLI profile.
200
+ - `--from-scan`: Path to JSON output from a previous `driftwatch scan --json`.
201
+
202
+ ---
203
+
204
+ ### 3. Remediate Drift (`driftwatch remediate`)
205
+ Safely reconcile live infrastructure back to Terraform IaC specifications:
206
+
207
+ ```bash
208
+ # Dry run mode for a specific resource (default)
209
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run
210
+
211
+ # Apply mode (requires interactive confirmation in prod/unrecognized environments)
212
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
213
+
214
+ # Batch remediation: Fix ALL detected drifted resources at once
215
+ driftwatch remediate --all --region ap-south-1 --apply
216
+
217
+ # Non-interactive CI/CD execution (auto-approve all prompts)
218
+ driftwatch remediate --all --region ap-south-1 --apply --yes
219
+
220
+ # Remediate from a saved scan (avoids re-scanning live AWS)
221
+ driftwatch remediate --all --from-scan scan_results.json --apply --yes
222
+ ```
223
+
224
+ **Options for `driftwatch remediate`:**
225
+ - `RESOURCE_ID`: Target resource ID (optional if `--all` is supplied).
226
+ - `--all`, `-a`: Remediate all detected drifted resources in batch.
227
+ - `--dry-run / --apply`: Dry run mode (default) or execute changes.
228
+ - `--yes`, `-y`, `--force`: Automatically approve prompts without confirmation (essential for CI runners and cron jobs).
229
+ - `--from-scan`: Path to saved scan JSON file.
230
+ - `--profile`: Named AWS CLI profile.
231
+
232
+ ---
233
+
234
+ ## 🐍 Python Engine API
235
+
236
+ You can also import and use DriftWatch programmatically:
237
+
238
+ ```python
239
+ from driftwatch.engine import detect_drift, get_severity, DriftType
240
+
241
+ # Or import directly from drift_engine
242
+ from drift_engine import detect_drift, get_severity
243
+
244
+ results, total_scanned = detect_drift(
245
+ tf_state_path="terraform/terraform.tfstate",
246
+ region="ap-south-1",
247
+ profile="default"
248
+ )
249
+
250
+ for r in results:
251
+ severity = get_severity(r.resource_type, r.drift_type, r.diff)
252
+ print(f"[{r.drift_type.value}] {r.resource_type} ({r.resource_id}) -> Severity: {severity}")
253
+ ```
254
+
255
+ ---
256
+
257
+ ## ⚠️ Security & Safety Guidelines
258
+
259
+ > [!WARNING]
260
+ > **Auto-Remediation Safety**:
261
+ > - Automated drift remediation without confirmation is intended for **Development** and **Staging** environments.
262
+ > - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and will safely fail-closed (`return False`) in non-interactive terminals unless an explicit `--yes` / `--force` flag is provided.
263
+ > - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to prevent unplanned database reboots.
264
+
265
+ ---
266
+
267
+ ## 🧪 Testing
268
+
269
+ Run the full test suite with coverage:
270
+ ```bash
271
+ pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
272
+ ```
273
+
274
+ ---
275
+
276
+ ## 📄 License
277
+
278
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,237 @@
1
+ # DriftWatch 🛡️
2
+
3
+ **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.
4
+
5
+ ---
6
+
7
+ ## 🚀 Key Features
8
+
9
+ - **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.
10
+ - **Data-Driven Severity Scoring**: Evaluates changes dynamically at the attribute level (e.g., security group open ingress ports vs. description updates) to classify drifts as `CRITICAL`, `HIGH`, `MEDIUM`, or `LOW`.
11
+ - **AI-Powered Risk Summaries**: Integrates with LLMs (Groq API) via lightweight direct HTTP requests to provide concise security analysis and compliance impact assessments.
12
+ - **Deterministic IaC Remediation**: Recommends safe, template-generated `terraform import` and `terraform apply` commands rather than hallucinated AI scripts.
13
+ - **Guarded Auto-Remediation**: Pre-flight validation checks for EC2 (EBS verification, Spot skip, running state), RDS maintenance-window defaults, and explicit interactive confirmations with `--yes` / `--force` automation overrides for CI/CD.
14
+ - **Batch Remediation & Scan Caching**: Remediate all drifted resources at once (`--all`), and pass scan outputs (`--from-scan`) to `explain` and `remediate` to avoid redundant AWS API sweeps.
15
+ - **Machine-Readable Outputs**: Export full scan reports in structured JSON format (`--json` or `--output json`).
16
+ - **Multi-Channel Alerting**: Instant notifications via Telegram, Slack, and Email.
17
+ - **Strict CI/CD Quality Gate**: Built-in gate enforcement (`--fail-on`) that halts pipelines with non-zero exit codes on threshold breaches, missing state, corrupted state, or AWS authentication failures.
18
+
19
+ ---
20
+
21
+ ## 🏛️ Architecture Overview
22
+
23
+ ```
24
+ driftwatch/
25
+ ├── drift_engine/ # Core drift detection & reconciliation engine
26
+ │ ├── __init__.py # Core exports (detect_drift, get_severity, models)
27
+ │ ├── aws_client.py # Live AWS discovery & Cost Explorer lookup (boto3)
28
+ │ ├── core.py # Diff evaluation & severity engine
29
+ │ ├── database.py # PostgreSQL scan history recorder (optional)
30
+ │ ├── explain.py # AI risk summaries & deterministic IaC templates
31
+ │ ├── models.py # Data models & attribute severity tables
32
+ │ ├── notifications.py # Alert dispatcher (Telegram, Slack, Email)
33
+ │ ├── remediation.py # Guarded auto-remediation handlers
34
+ │ └── tf_parser.py # Terraform state JSON parser
35
+ ├── driftwatch/ # CLI Entrypoint (Typer)
36
+ │ ├── __init__.py # Package version & engine alias (driftwatch.engine)
37
+ │ └── cli.py # Commands: scan, explain, remediate
38
+ ├── terraform/ # Example infrastructure and state configuration
39
+ ├── kubernetes/ # Kubernetes CronJob deployment
40
+ └── tests/ # Comprehensive unit tests with moto AWS mocks
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 📋 Prerequisites
46
+
47
+ - **Python**: `>= 3.10`
48
+ - **AWS Credentials**: Configured via environment variables, IAM roles, or AWS CLI profiles (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`, or `--profile`).
49
+ - **Terraform State File**: Local JSON state or remote state (`terraform.tfstate`).
50
+ - **PostgreSQL** *(Optional)*: For persistent scan audit history.
51
+ - **Groq API Key** *(Optional)*: `GROQ_API_KEY` for AI risk explanations.
52
+
53
+ ---
54
+
55
+ ## 📦 Installation
56
+
57
+ ### From PyPI (Recommended)
58
+ ```bash
59
+ pip install driftwatch-cli
60
+
61
+ # With PostgreSQL support for persistent audit history
62
+ pip install "driftwatch-cli[postgres]"
63
+ ```
64
+
65
+ ### From Source (Local Development)
66
+ ```bash
67
+ git clone https://github.com/hastagnitin/driftwatch.git
68
+ cd driftwatch
69
+ pip install -e .[dev]
70
+ ```
71
+
72
+ ---
73
+
74
+ ## ⚙️ Configuration
75
+
76
+ Create a `.env` file in the root directory:
77
+
78
+ ```env
79
+ AWS_DEFAULT_REGION=ap-south-1
80
+ TF_STATE_PATH=terraform/terraform.tfstate
81
+
82
+ # Optional: AWS Named Profile
83
+ # AWS_PROFILE=prod-profile
84
+
85
+ # Optional: AI Risk Summaries
86
+ GROQ_API_KEY=your_groq_api_key
87
+
88
+ # Optional: Notifications
89
+ SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
90
+ TELEGRAM_BOT_TOKEN=your_telegram_bot_token
91
+ TELEGRAM_CHAT_ID=your_telegram_chat_id
92
+
93
+ # Optional: PostgreSQL Database
94
+ DB_HOST=localhost
95
+ DB_PORT=5432
96
+ DB_NAME=driftwatch
97
+ DB_USER=postgres
98
+ DB_PASSWORD=your_db_password
99
+ ```
100
+
101
+ ---
102
+
103
+ ## 💻 Usage & CLI Commands
104
+
105
+ Check CLI version and help:
106
+ ```bash
107
+ driftwatch --version # or: driftwatch -v
108
+ driftwatch --help # or: driftwatch -h
109
+ ```
110
+
111
+ ### 1. Scan for Drift (`driftwatch scan`)
112
+ Scan live AWS infrastructure against your Terraform state:
113
+
114
+ ```bash
115
+ # Standard scan
116
+ driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate
117
+
118
+ # Using a named AWS profile
119
+ driftwatch scan --region us-east-1 --profile staging-admin
120
+
121
+ # CI/CD Drift Gate (fails build with exit code 1 if CRITICAL drift is detected)
122
+ driftwatch scan --region ap-south-1 --fail-on CRITICAL
123
+
124
+ # Output as structured JSON (for dashboards or piped automation)
125
+ driftwatch scan --region ap-south-1 --output json > scan_results.json
126
+ # Or use shorthand:
127
+ driftwatch scan --region ap-south-1 --json > scan_results.json
128
+ ```
129
+
130
+ **Options for `driftwatch scan`:**
131
+ - `--state`: Path to Terraform state file (default: `terraform/terraform.tfstate`).
132
+ - `--region`: Target AWS region (or defaults to `AWS_DEFAULT_REGION`).
133
+ - `--profile`: Named AWS CLI profile to use for credentials.
134
+ - `--fail-on`: Severity threshold to trigger non-zero exit code (`LOW`, `MEDIUM`, `HIGH`, `CRITICAL`). Case-insensitive.
135
+ - `--output`, `-o`: Output format: `text` (default) or `json`.
136
+ - `--json`: Shorthand flag for `--output json`.
137
+
138
+ > [!NOTE]
139
+ > **CI Gate Reliability**: If the Terraform state file is missing or corrupted, or if live AWS resource fetching fails (e.g. invalid credentials or expired sessions), `driftwatch scan` immediately aborts with a non-zero exit code (`1`), preventing false-green builds in your CI/CD pipeline.
140
+
141
+ ---
142
+
143
+ ### 2. Explain Drift (`driftwatch explain`)
144
+ Generate AI risk analysis and deterministic IaC fix recommendations for a drifted resource:
145
+
146
+ ```bash
147
+ # Live query (fetches live AWS state for resource)
148
+ driftwatch explain sg-0123456789abcdef0 --region ap-south-1
149
+
150
+ # Zero-sweep query from previous scan file (instant, 0 AWS API calls)
151
+ driftwatch explain sg-0123456789abcdef0 --from-scan scan_results.json
152
+ ```
153
+
154
+ **Options for `driftwatch explain`:**
155
+ - `RESOURCE_ID`: ID of the resource to explain (e.g. `sg-xxx`, `i-xxx`).
156
+ - `--state`: Path to Terraform state file.
157
+ - `--region`: Target AWS region.
158
+ - `--profile`: Named AWS CLI profile.
159
+ - `--from-scan`: Path to JSON output from a previous `driftwatch scan --json`.
160
+
161
+ ---
162
+
163
+ ### 3. Remediate Drift (`driftwatch remediate`)
164
+ Safely reconcile live infrastructure back to Terraform IaC specifications:
165
+
166
+ ```bash
167
+ # Dry run mode for a specific resource (default)
168
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run
169
+
170
+ # Apply mode (requires interactive confirmation in prod/unrecognized environments)
171
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
172
+
173
+ # Batch remediation: Fix ALL detected drifted resources at once
174
+ driftwatch remediate --all --region ap-south-1 --apply
175
+
176
+ # Non-interactive CI/CD execution (auto-approve all prompts)
177
+ driftwatch remediate --all --region ap-south-1 --apply --yes
178
+
179
+ # Remediate from a saved scan (avoids re-scanning live AWS)
180
+ driftwatch remediate --all --from-scan scan_results.json --apply --yes
181
+ ```
182
+
183
+ **Options for `driftwatch remediate`:**
184
+ - `RESOURCE_ID`: Target resource ID (optional if `--all` is supplied).
185
+ - `--all`, `-a`: Remediate all detected drifted resources in batch.
186
+ - `--dry-run / --apply`: Dry run mode (default) or execute changes.
187
+ - `--yes`, `-y`, `--force`: Automatically approve prompts without confirmation (essential for CI runners and cron jobs).
188
+ - `--from-scan`: Path to saved scan JSON file.
189
+ - `--profile`: Named AWS CLI profile.
190
+
191
+ ---
192
+
193
+ ## 🐍 Python Engine API
194
+
195
+ You can also import and use DriftWatch programmatically:
196
+
197
+ ```python
198
+ from driftwatch.engine import detect_drift, get_severity, DriftType
199
+
200
+ # Or import directly from drift_engine
201
+ from drift_engine import detect_drift, get_severity
202
+
203
+ results, total_scanned = detect_drift(
204
+ tf_state_path="terraform/terraform.tfstate",
205
+ region="ap-south-1",
206
+ profile="default"
207
+ )
208
+
209
+ for r in results:
210
+ severity = get_severity(r.resource_type, r.drift_type, r.diff)
211
+ print(f"[{r.drift_type.value}] {r.resource_type} ({r.resource_id}) -> Severity: {severity}")
212
+ ```
213
+
214
+ ---
215
+
216
+ ## ⚠️ Security & Safety Guidelines
217
+
218
+ > [!WARNING]
219
+ > **Auto-Remediation Safety**:
220
+ > - Automated drift remediation without confirmation is intended for **Development** and **Staging** environments.
221
+ > - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and will safely fail-closed (`return False`) in non-interactive terminals unless an explicit `--yes` / `--force` flag is provided.
222
+ > - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to prevent unplanned database reboots.
223
+
224
+ ---
225
+
226
+ ## 🧪 Testing
227
+
228
+ Run the full test suite with coverage:
229
+ ```bash
230
+ pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
231
+ ```
232
+
233
+ ---
234
+
235
+ ## 📄 License
236
+
237
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,17 @@
1
+ """DriftWatch Core Engine
2
+
3
+ Provides multi-resource Terraform infrastructure drift detection, diff calculation,
4
+ data-driven severity scoring, and guarded remediation handlers.
5
+ """
6
+
7
+ from drift_engine.core import detect_drift, get_severity
8
+ from drift_engine.models import DriftResult, DriftType, MONITORED_ATTRIBUTES, ATTRIBUTE_SEVERITY
9
+
10
+ __all__ = [
11
+ "detect_drift",
12
+ "get_severity",
13
+ "DriftResult",
14
+ "DriftType",
15
+ "MONITORED_ATTRIBUTES",
16
+ "ATTRIBUTE_SEVERITY",
17
+ ]