driftwatch-cli 0.1.0__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.
- driftwatch_cli-0.1.0/LICENSE +21 -0
- driftwatch_cli-0.1.0/PKG-INFO +165 -0
- driftwatch_cli-0.1.0/README.md +139 -0
- driftwatch_cli-0.1.0/drift_engine/__init__.py +0 -0
- driftwatch_cli-0.1.0/drift_engine/aws_client.py +241 -0
- driftwatch_cli-0.1.0/drift_engine/core.py +190 -0
- driftwatch_cli-0.1.0/drift_engine/database.py +54 -0
- driftwatch_cli-0.1.0/drift_engine/explain.py +72 -0
- driftwatch_cli-0.1.0/drift_engine/models.py +65 -0
- driftwatch_cli-0.1.0/drift_engine/notifications.py +114 -0
- driftwatch_cli-0.1.0/drift_engine/remediation.py +273 -0
- driftwatch_cli-0.1.0/drift_engine/tf_parser.py +70 -0
- driftwatch_cli-0.1.0/driftwatch/__init__.py +0 -0
- driftwatch_cli-0.1.0/driftwatch/cli.py +194 -0
- driftwatch_cli-0.1.0/driftwatch_cli.egg-info/PKG-INFO +165 -0
- driftwatch_cli-0.1.0/driftwatch_cli.egg-info/SOURCES.txt +25 -0
- driftwatch_cli-0.1.0/driftwatch_cli.egg-info/dependency_links.txt +1 -0
- driftwatch_cli-0.1.0/driftwatch_cli.egg-info/entry_points.txt +2 -0
- driftwatch_cli-0.1.0/driftwatch_cli.egg-info/requires.txt +14 -0
- driftwatch_cli-0.1.0/driftwatch_cli.egg-info/top_level.txt +2 -0
- driftwatch_cli-0.1.0/pyproject.toml +42 -0
- driftwatch_cli-0.1.0/setup.cfg +4 -0
- driftwatch_cli-0.1.0/tests/test_aws_client.py +148 -0
- driftwatch_cli-0.1.0/tests/test_cli.py +167 -0
- driftwatch_cli-0.1.0/tests/test_diff_engine.py +205 -0
- driftwatch_cli-0.1.0/tests/test_explain_notifications.py +157 -0
- driftwatch_cli-0.1.0/tests/test_remediation.py +274 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nitin Gupta
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: driftwatch-cli
|
|
3
|
+
Version: 0.1.0
|
|
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
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: boto3>=1.34.0
|
|
13
|
+
Requires-Dist: typer>=0.9.0
|
|
14
|
+
Requires-Dist: groq>=0.4.0
|
|
15
|
+
Requires-Dist: python-telegram-bot>=20.0
|
|
16
|
+
Requires-Dist: psycopg2-binary>=2.9.0
|
|
17
|
+
Requires-Dist: requests>=2.31.0
|
|
18
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
21
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
22
|
+
Requires-Dist: moto[all]>=5.0.0; extra == "dev"
|
|
23
|
+
Requires-Dist: build; extra == "dev"
|
|
24
|
+
Requires-Dist: twine; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# DriftWatch 🛡️
|
|
28
|
+
|
|
29
|
+
**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.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 🚀 Key Features
|
|
34
|
+
|
|
35
|
+
- **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.
|
|
36
|
+
- **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`.
|
|
37
|
+
- **AI-Powered Risk Summaries**: Integrates with LLMs to provide plain-English security analysis and compliance impact assessments.
|
|
38
|
+
- **Deterministic IaC Remediation**: Recommends safe, template-generated `terraform import` and `terraform apply` commands rather than hallucinated AI outputs.
|
|
39
|
+
- **Guarded Auto-Remediation**: Pre-flight validation checks for EC2 (EBS verification, Spot skip, running state), RDS maintenance-window defaults, and explicit interactive confirmations.
|
|
40
|
+
- **Multi-Channel Alerting**: Instant notifications via Telegram, Slack, and Email.
|
|
41
|
+
- **CI/CD Quality Gate**: Built-in GitHub Actions integration to enforce zero-tolerance drift policies in pull requests.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 🏛️ Architecture Overview
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
driftwatch/
|
|
49
|
+
├── drift_engine/ # Core drift detection & reconciliation engine
|
|
50
|
+
│ ├── aws_client.py # Live AWS resource discovery (boto3)
|
|
51
|
+
│ ├── core.py # Diff evaluation & data-driven severity engine
|
|
52
|
+
│ ├── database.py # PostgreSQL scan history recorder
|
|
53
|
+
│ ├── explain.py # AI risk summaries & deterministic IaC templates
|
|
54
|
+
│ ├── models.py # Data models & attribute severity tables
|
|
55
|
+
│ ├── notifications.py # Alert dispatcher (Telegram, Slack, Email)
|
|
56
|
+
│ ├── remediation.py # Guarded auto-remediation handlers
|
|
57
|
+
│ └── tf_parser.py # Terraform state JSON parser
|
|
58
|
+
├── driftwatch/ # CLI Entrypoint (Typer)
|
|
59
|
+
│ └── cli.py # Command definitions: scan, explain, remediate
|
|
60
|
+
├── terraform/ # Example infrastructure and state configuration
|
|
61
|
+
├── kubernetes/ # Kubernetes CronJob deployment
|
|
62
|
+
└── tests/ # Comprehensive unit tests with moto AWS mocks
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## 📋 Prerequisites
|
|
68
|
+
|
|
69
|
+
- **Python**: `>= 3.10`
|
|
70
|
+
- **AWS Credentials**: Configured via environment variables, IAM roles, or AWS CLI credentials (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`).
|
|
71
|
+
- **Terraform State File**: Local JSON state or remote state (`terraform.tfstate`).
|
|
72
|
+
- **PostgreSQL** *(Optional)*: For persistent scan audit history.
|
|
73
|
+
- **Groq API Key** *(Optional)*: `GROQ_API_KEY` for AI risk explanations.
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## 📦 Installation
|
|
78
|
+
|
|
79
|
+
### From Source (Local Development)
|
|
80
|
+
```bash
|
|
81
|
+
git clone https://github.com/hastagnitin/driftwatch.git
|
|
82
|
+
cd driftwatch
|
|
83
|
+
pip install -e .[dev]
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## ⚙️ Configuration
|
|
89
|
+
|
|
90
|
+
Create a `.env` file in the root directory:
|
|
91
|
+
|
|
92
|
+
```env
|
|
93
|
+
AWS_DEFAULT_REGION=ap-south-1
|
|
94
|
+
TF_STATE_PATH=terraform/terraform.tfstate
|
|
95
|
+
|
|
96
|
+
# Optional: AI Risk Summaries
|
|
97
|
+
GROQ_API_KEY=your_groq_api_key
|
|
98
|
+
|
|
99
|
+
# Optional: Notifications
|
|
100
|
+
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
|
|
101
|
+
TELEGRAM_BOT_TOKEN=your_telegram_bot_token
|
|
102
|
+
TELEGRAM_CHAT_ID=your_telegram_chat_id
|
|
103
|
+
|
|
104
|
+
# Optional: PostgreSQL Database
|
|
105
|
+
DB_HOST=localhost
|
|
106
|
+
DB_PORT=5432
|
|
107
|
+
DB_NAME=driftwatch
|
|
108
|
+
DB_USER=postgres
|
|
109
|
+
DB_PASSWORD=your_db_password
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
## 💻 Usage & CLI Commands
|
|
115
|
+
|
|
116
|
+
### 1. Scan for Drift
|
|
117
|
+
Scan live AWS infrastructure against your Terraform state:
|
|
118
|
+
```bash
|
|
119
|
+
# Basic scan
|
|
120
|
+
driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate
|
|
121
|
+
|
|
122
|
+
# Enforce CI Gate (fails build if CRITICAL drift is found)
|
|
123
|
+
driftwatch scan --region ap-south-1 --fail-on CRITICAL
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### 2. Explain Drift
|
|
127
|
+
Generate AI risk analysis and deterministic IaC fix recommendations:
|
|
128
|
+
```bash
|
|
129
|
+
driftwatch explain sg-0123456789abcdef0 --region ap-south-1
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### 3. Remediate Drift
|
|
133
|
+
Safely remediate drifted resources back to IaC specifications:
|
|
134
|
+
```bash
|
|
135
|
+
# Dry run mode (default)
|
|
136
|
+
driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run
|
|
137
|
+
|
|
138
|
+
# Apply mode with interactive confirmation
|
|
139
|
+
driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
## ⚠️ Security & Safety Guidelines
|
|
145
|
+
|
|
146
|
+
> [!WARNING]
|
|
147
|
+
> **Auto-Remediation Safety**:
|
|
148
|
+
> - Automated drift remediation is intended for **Development** and **Staging** environments.
|
|
149
|
+
> - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and recommends template-generated `terraform apply` / `terraform import` workflows.
|
|
150
|
+
> - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to avoid unplanned reboots.
|
|
151
|
+
|
|
152
|
+
---
|
|
153
|
+
|
|
154
|
+
## 🧪 Testing
|
|
155
|
+
|
|
156
|
+
Run the test suite with test coverage:
|
|
157
|
+
```bash
|
|
158
|
+
pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## 📄 License
|
|
164
|
+
|
|
165
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
@@ -0,0 +1,139 @@
|
|
|
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 ports vs description updates) to classify drifts as `CRITICAL`, `HIGH`, `MEDIUM`, or `LOW`.
|
|
11
|
+
- **AI-Powered Risk Summaries**: Integrates with LLMs to provide plain-English security analysis and compliance impact assessments.
|
|
12
|
+
- **Deterministic IaC Remediation**: Recommends safe, template-generated `terraform import` and `terraform apply` commands rather than hallucinated AI outputs.
|
|
13
|
+
- **Guarded Auto-Remediation**: Pre-flight validation checks for EC2 (EBS verification, Spot skip, running state), RDS maintenance-window defaults, and explicit interactive confirmations.
|
|
14
|
+
- **Multi-Channel Alerting**: Instant notifications via Telegram, Slack, and Email.
|
|
15
|
+
- **CI/CD Quality Gate**: Built-in GitHub Actions integration to enforce zero-tolerance drift policies in pull requests.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## 🏛️ Architecture Overview
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
driftwatch/
|
|
23
|
+
├── drift_engine/ # Core drift detection & reconciliation engine
|
|
24
|
+
│ ├── aws_client.py # Live AWS resource discovery (boto3)
|
|
25
|
+
│ ├── core.py # Diff evaluation & data-driven severity engine
|
|
26
|
+
│ ├── database.py # PostgreSQL scan history recorder
|
|
27
|
+
│ ├── explain.py # AI risk summaries & deterministic IaC templates
|
|
28
|
+
│ ├── models.py # Data models & attribute severity tables
|
|
29
|
+
│ ├── notifications.py # Alert dispatcher (Telegram, Slack, Email)
|
|
30
|
+
│ ├── remediation.py # Guarded auto-remediation handlers
|
|
31
|
+
│ └── tf_parser.py # Terraform state JSON parser
|
|
32
|
+
├── driftwatch/ # CLI Entrypoint (Typer)
|
|
33
|
+
│ └── cli.py # Command definitions: scan, explain, remediate
|
|
34
|
+
├── terraform/ # Example infrastructure and state configuration
|
|
35
|
+
├── kubernetes/ # Kubernetes CronJob deployment
|
|
36
|
+
└── tests/ # Comprehensive unit tests with moto AWS mocks
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## 📋 Prerequisites
|
|
42
|
+
|
|
43
|
+
- **Python**: `>= 3.10`
|
|
44
|
+
- **AWS Credentials**: Configured via environment variables, IAM roles, or AWS CLI credentials (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`).
|
|
45
|
+
- **Terraform State File**: Local JSON state or remote state (`terraform.tfstate`).
|
|
46
|
+
- **PostgreSQL** *(Optional)*: For persistent scan audit history.
|
|
47
|
+
- **Groq API Key** *(Optional)*: `GROQ_API_KEY` for AI risk explanations.
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## 📦 Installation
|
|
52
|
+
|
|
53
|
+
### From Source (Local Development)
|
|
54
|
+
```bash
|
|
55
|
+
git clone https://github.com/hastagnitin/driftwatch.git
|
|
56
|
+
cd driftwatch
|
|
57
|
+
pip install -e .[dev]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## ⚙️ Configuration
|
|
63
|
+
|
|
64
|
+
Create a `.env` file in the root directory:
|
|
65
|
+
|
|
66
|
+
```env
|
|
67
|
+
AWS_DEFAULT_REGION=ap-south-1
|
|
68
|
+
TF_STATE_PATH=terraform/terraform.tfstate
|
|
69
|
+
|
|
70
|
+
# Optional: AI Risk Summaries
|
|
71
|
+
GROQ_API_KEY=your_groq_api_key
|
|
72
|
+
|
|
73
|
+
# Optional: Notifications
|
|
74
|
+
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
|
|
75
|
+
TELEGRAM_BOT_TOKEN=your_telegram_bot_token
|
|
76
|
+
TELEGRAM_CHAT_ID=your_telegram_chat_id
|
|
77
|
+
|
|
78
|
+
# Optional: PostgreSQL Database
|
|
79
|
+
DB_HOST=localhost
|
|
80
|
+
DB_PORT=5432
|
|
81
|
+
DB_NAME=driftwatch
|
|
82
|
+
DB_USER=postgres
|
|
83
|
+
DB_PASSWORD=your_db_password
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## 💻 Usage & CLI Commands
|
|
89
|
+
|
|
90
|
+
### 1. Scan for Drift
|
|
91
|
+
Scan live AWS infrastructure against your Terraform state:
|
|
92
|
+
```bash
|
|
93
|
+
# Basic scan
|
|
94
|
+
driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate
|
|
95
|
+
|
|
96
|
+
# Enforce CI Gate (fails build if CRITICAL drift is found)
|
|
97
|
+
driftwatch scan --region ap-south-1 --fail-on CRITICAL
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### 2. Explain Drift
|
|
101
|
+
Generate AI risk analysis and deterministic IaC fix recommendations:
|
|
102
|
+
```bash
|
|
103
|
+
driftwatch explain sg-0123456789abcdef0 --region ap-south-1
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### 3. Remediate Drift
|
|
107
|
+
Safely remediate drifted resources back to IaC specifications:
|
|
108
|
+
```bash
|
|
109
|
+
# Dry run mode (default)
|
|
110
|
+
driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run
|
|
111
|
+
|
|
112
|
+
# Apply mode with interactive confirmation
|
|
113
|
+
driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## ⚠️ Security & Safety Guidelines
|
|
119
|
+
|
|
120
|
+
> [!WARNING]
|
|
121
|
+
> **Auto-Remediation Safety**:
|
|
122
|
+
> - Automated drift remediation is intended for **Development** and **Staging** environments.
|
|
123
|
+
> - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and recommends template-generated `terraform apply` / `terraform import` workflows.
|
|
124
|
+
> - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to avoid unplanned reboots.
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
## 🧪 Testing
|
|
129
|
+
|
|
130
|
+
Run the test suite with test coverage:
|
|
131
|
+
```bash
|
|
132
|
+
pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
---
|
|
136
|
+
|
|
137
|
+
## 📄 License
|
|
138
|
+
|
|
139
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
File without changes
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import boto3
|
|
3
|
+
from datetime import datetime, timedelta
|
|
4
|
+
|
|
5
|
+
def fetch_live_ec2_instances(region: str) -> dict:
|
|
6
|
+
ec2 = boto3.client("ec2", region_name=region)
|
|
7
|
+
live = {}
|
|
8
|
+
try:
|
|
9
|
+
paginator = ec2.get_paginator("describe_instances")
|
|
10
|
+
for page in paginator.paginate():
|
|
11
|
+
for reservation in page.get("Reservations", []):
|
|
12
|
+
for instance in reservation.get("Instances", []):
|
|
13
|
+
if instance.get("State", {}).get("Name") == "terminated":
|
|
14
|
+
continue
|
|
15
|
+
|
|
16
|
+
tags_list = instance.get("Tags", [])
|
|
17
|
+
tags_dict = {t["Key"]: t["Value"] for t in tags_list if "Key" in t and "Value" in t}
|
|
18
|
+
name = tags_dict.get("Name", "Unknown")
|
|
19
|
+
|
|
20
|
+
sg_ids = []
|
|
21
|
+
for sg in instance.get("SecurityGroups", []):
|
|
22
|
+
if "GroupId" in sg:
|
|
23
|
+
sg_ids.append(sg.get("GroupId"))
|
|
24
|
+
sg_ids.sort()
|
|
25
|
+
|
|
26
|
+
instance_id = instance["InstanceId"]
|
|
27
|
+
live[instance_id] = {
|
|
28
|
+
"type": "aws_instance",
|
|
29
|
+
"name": name,
|
|
30
|
+
"attributes": {
|
|
31
|
+
"id": instance_id,
|
|
32
|
+
"instance_type": instance.get("InstanceType"),
|
|
33
|
+
"ami": instance.get("ImageId"),
|
|
34
|
+
"tags": tags_dict,
|
|
35
|
+
"vpc_security_group_ids": sg_ids
|
|
36
|
+
},
|
|
37
|
+
}
|
|
38
|
+
except Exception as e:
|
|
39
|
+
print(f"Failed to fetch aws_instance: {e}", file=sys.stderr)
|
|
40
|
+
return None
|
|
41
|
+
return live
|
|
42
|
+
|
|
43
|
+
def fetch_live_s3_buckets(region: str) -> dict:
|
|
44
|
+
s3 = boto3.client("s3", region_name=region)
|
|
45
|
+
live = {}
|
|
46
|
+
try:
|
|
47
|
+
response = s3.list_buckets()
|
|
48
|
+
for bucket in response.get("Buckets", []):
|
|
49
|
+
bucket_name = bucket["Name"]
|
|
50
|
+
try:
|
|
51
|
+
tags_response = s3.get_bucket_tagging(Bucket=bucket_name)
|
|
52
|
+
tags_list = tags_response.get("TagSet", [])
|
|
53
|
+
tags_dict = {t["Key"]: t["Value"] for t in tags_list if "Key" in t and "Value" in t}
|
|
54
|
+
name = tags_dict.get("Name", bucket_name)
|
|
55
|
+
except Exception:
|
|
56
|
+
tags_dict = {}
|
|
57
|
+
name = bucket_name
|
|
58
|
+
|
|
59
|
+
live[bucket_name] = {
|
|
60
|
+
"type": "aws_s3_bucket",
|
|
61
|
+
"name": name,
|
|
62
|
+
"attributes": {
|
|
63
|
+
"id": bucket_name,
|
|
64
|
+
"bucket": bucket_name,
|
|
65
|
+
"tags": tags_dict,
|
|
66
|
+
},
|
|
67
|
+
}
|
|
68
|
+
except Exception as e:
|
|
69
|
+
print(f"Failed to fetch aws_s3_bucket: {e}", file=sys.stderr)
|
|
70
|
+
return None
|
|
71
|
+
return live
|
|
72
|
+
|
|
73
|
+
def fetch_live_security_groups(region: str) -> dict:
|
|
74
|
+
ec2 = boto3.client("ec2", region_name=region)
|
|
75
|
+
live = {}
|
|
76
|
+
try:
|
|
77
|
+
paginator = ec2.get_paginator("describe_security_groups")
|
|
78
|
+
for page in paginator.paginate():
|
|
79
|
+
for sg in page.get("SecurityGroups", []):
|
|
80
|
+
sg_id = sg["GroupId"]
|
|
81
|
+
sg_name = sg.get("GroupName", "")
|
|
82
|
+
|
|
83
|
+
tags_list = sg.get("Tags", [])
|
|
84
|
+
tags_dict = {t["Key"]: t["Value"] for t in tags_list if "Key" in t and "Value" in t}
|
|
85
|
+
name_tag = tags_dict.get("Name", sg_name)
|
|
86
|
+
|
|
87
|
+
ingress_rules = []
|
|
88
|
+
for perm in sg.get("IpPermissions", []):
|
|
89
|
+
cidrs = [ip.get("CidrIp") for ip in perm.get("IpRanges", []) if ip.get("CidrIp")]
|
|
90
|
+
if cidrs:
|
|
91
|
+
ingress_rules.append({
|
|
92
|
+
"from_port": perm.get("FromPort", 0),
|
|
93
|
+
"to_port": perm.get("ToPort", 0),
|
|
94
|
+
"protocol": perm.get("IpProtocol", "-1"),
|
|
95
|
+
"cidr_blocks": cidrs
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
egress_rules = []
|
|
99
|
+
for perm in sg.get("IpPermissionsEgress", []):
|
|
100
|
+
cidrs = [ip.get("CidrIp") for ip in perm.get("IpRanges", []) if ip.get("CidrIp")]
|
|
101
|
+
if cidrs:
|
|
102
|
+
egress_rules.append({
|
|
103
|
+
"from_port": perm.get("FromPort", 0),
|
|
104
|
+
"to_port": perm.get("ToPort", 0),
|
|
105
|
+
"protocol": perm.get("IpProtocol", "-1"),
|
|
106
|
+
"cidr_blocks": cidrs
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
live[sg_id] = {
|
|
110
|
+
"type": "aws_security_group",
|
|
111
|
+
"name": name_tag,
|
|
112
|
+
"attributes": {
|
|
113
|
+
"id": sg_id,
|
|
114
|
+
"name": sg_name,
|
|
115
|
+
"description": sg.get("Description", ""),
|
|
116
|
+
"tags": tags_dict,
|
|
117
|
+
"ingress": ingress_rules,
|
|
118
|
+
"egress": egress_rules,
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
except Exception as e:
|
|
122
|
+
print(f"Failed to fetch aws_security_group: {e}", file=sys.stderr)
|
|
123
|
+
return None
|
|
124
|
+
return live
|
|
125
|
+
|
|
126
|
+
def fetch_live_rds_instances(region: str) -> dict:
|
|
127
|
+
rds = boto3.client("rds", region_name=region)
|
|
128
|
+
live = {}
|
|
129
|
+
try:
|
|
130
|
+
paginator = rds.get_paginator("describe_db_instances")
|
|
131
|
+
for page in paginator.paginate():
|
|
132
|
+
for db in page.get("DBInstances", []):
|
|
133
|
+
db_id = db.get("DBInstanceIdentifier")
|
|
134
|
+
if not db_id:
|
|
135
|
+
continue
|
|
136
|
+
live[db_id] = {
|
|
137
|
+
"type": "aws_db_instance",
|
|
138
|
+
"name": db_id,
|
|
139
|
+
"attributes": {
|
|
140
|
+
"id": db_id,
|
|
141
|
+
"identifier": db_id,
|
|
142
|
+
"allocated_storage": db.get("AllocatedStorage"),
|
|
143
|
+
"engine": db.get("Engine"),
|
|
144
|
+
"engine_version": db.get("EngineVersion"),
|
|
145
|
+
"instance_class": db.get("DBInstanceClass"),
|
|
146
|
+
"multi_az": db.get("MultiAZ"),
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
except Exception as e:
|
|
150
|
+
print(f"Failed to fetch aws_db_instance: {e}", file=sys.stderr)
|
|
151
|
+
return None
|
|
152
|
+
return live
|
|
153
|
+
|
|
154
|
+
def fetch_live_lambda_functions(region: str) -> dict:
|
|
155
|
+
lambda_client = boto3.client("lambda", region_name=region)
|
|
156
|
+
live = {}
|
|
157
|
+
try:
|
|
158
|
+
paginator = lambda_client.get_paginator("list_functions")
|
|
159
|
+
for page in paginator.paginate():
|
|
160
|
+
for func in page.get("Functions", []):
|
|
161
|
+
func_name = func.get("FunctionName")
|
|
162
|
+
if not func_name:
|
|
163
|
+
continue
|
|
164
|
+
live[func_name] = {
|
|
165
|
+
"type": "aws_lambda_function",
|
|
166
|
+
"name": func_name,
|
|
167
|
+
"attributes": {
|
|
168
|
+
"id": func_name,
|
|
169
|
+
"function_name": func_name,
|
|
170
|
+
"runtime": func.get("Runtime"),
|
|
171
|
+
"handler": func.get("Handler"),
|
|
172
|
+
"memory_size": func.get("MemorySize"),
|
|
173
|
+
"timeout": func.get("Timeout"),
|
|
174
|
+
"role": func.get("Role"),
|
|
175
|
+
},
|
|
176
|
+
}
|
|
177
|
+
except Exception as e:
|
|
178
|
+
print(f"Failed to fetch aws_lambda_function: {e}", file=sys.stderr)
|
|
179
|
+
return None
|
|
180
|
+
return live
|
|
181
|
+
|
|
182
|
+
def fetch_live_iam_roles(region: str) -> dict:
|
|
183
|
+
iam = boto3.client("iam", region_name=region)
|
|
184
|
+
live = {}
|
|
185
|
+
try:
|
|
186
|
+
paginator = iam.get_paginator("list_roles")
|
|
187
|
+
for page in paginator.paginate():
|
|
188
|
+
for role in page.get("Roles", []):
|
|
189
|
+
role_name = role.get("RoleName")
|
|
190
|
+
if not role_name:
|
|
191
|
+
continue
|
|
192
|
+
if role_name.startswith("AWSServiceRoleFor") or role.get("Path", "").startswith("/aws-service-role/"):
|
|
193
|
+
continue
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
policies = iam.list_attached_role_policies(RoleName=role_name)
|
|
197
|
+
attached_policies = sorted(
|
|
198
|
+
p["PolicyArn"] for p in policies.get("AttachedPolicies", []) if "PolicyArn" in p
|
|
199
|
+
)
|
|
200
|
+
except Exception:
|
|
201
|
+
attached_policies = []
|
|
202
|
+
|
|
203
|
+
live[role_name] = {
|
|
204
|
+
"type": "aws_iam_role",
|
|
205
|
+
"name": role_name,
|
|
206
|
+
"attributes": {
|
|
207
|
+
"id": role_name,
|
|
208
|
+
"name": role_name,
|
|
209
|
+
"path": role.get("Path", "/"),
|
|
210
|
+
"arn": role.get("Arn", ""),
|
|
211
|
+
"attached_policies": attached_policies
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
except Exception as e:
|
|
215
|
+
print(f"Failed to fetch aws_iam_role: {e}", file=sys.stderr)
|
|
216
|
+
return None
|
|
217
|
+
return live
|
|
218
|
+
|
|
219
|
+
def get_resource_cost(resource_id: str) -> float:
|
|
220
|
+
try:
|
|
221
|
+
client = boto3.client("ce", region_name="us-east-1")
|
|
222
|
+
|
|
223
|
+
end_date = datetime.today().strftime("%Y-%m-%d")
|
|
224
|
+
start_date = (datetime.today() - timedelta(days=30)).strftime("%Y-%m-%d")
|
|
225
|
+
|
|
226
|
+
response = client.get_cost_and_usage(
|
|
227
|
+
TimePeriod={"Start": start_date, "End": end_date},
|
|
228
|
+
Granularity="MONTHLY",
|
|
229
|
+
Metrics=["UnblendedCost"],
|
|
230
|
+
Filter={
|
|
231
|
+
"Dimensions": {
|
|
232
|
+
"Key": "RESOURCE_ID",
|
|
233
|
+
"Values": [resource_id]
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
usd_cost = float(response["ResultsByTime"][0]["Total"]["UnblendedCost"]["Amount"])
|
|
239
|
+
return usd_cost
|
|
240
|
+
except Exception:
|
|
241
|
+
return 0.0
|