driftwatch-cli 3.0.0__tar.gz → 3.0.2__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 (38) hide show
  1. driftwatch_cli-3.0.2/PKG-INFO +181 -0
  2. driftwatch_cli-3.0.2/README.md +144 -0
  3. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/drift_engine/aws_client.py +107 -68
  4. driftwatch_cli-3.0.2/drift_engine/core.py +190 -0
  5. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/drift_engine/database.py +22 -6
  6. driftwatch_cli-3.0.2/drift_engine/explain.py +72 -0
  7. driftwatch_cli-3.0.2/drift_engine/models.py +65 -0
  8. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/drift_engine/notifications.py +25 -32
  9. driftwatch_cli-3.0.2/drift_engine/remediation.py +284 -0
  10. driftwatch_cli-3.0.2/drift_engine/tf_parser.py +68 -0
  11. driftwatch_cli-3.0.2/driftwatch/cli.py +367 -0
  12. driftwatch_cli-3.0.2/driftwatch_cli.egg-info/PKG-INFO +181 -0
  13. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/driftwatch_cli.egg-info/SOURCES.txt +6 -1
  14. driftwatch_cli-3.0.2/driftwatch_cli.egg-info/requires.txt +14 -0
  15. driftwatch_cli-3.0.2/pyproject.toml +56 -0
  16. driftwatch_cli-3.0.2/tests/test_aws_client.py +148 -0
  17. driftwatch_cli-3.0.2/tests/test_cli.py +414 -0
  18. driftwatch_cli-3.0.2/tests/test_diff_engine.py +207 -0
  19. driftwatch_cli-3.0.2/tests/test_explain_notifications.py +173 -0
  20. driftwatch_cli-3.0.2/tests/test_remediation.py +284 -0
  21. driftwatch_cli-3.0.0/PKG-INFO +0 -13
  22. driftwatch_cli-3.0.0/drift_engine/core.py +0 -209
  23. driftwatch_cli-3.0.0/drift_engine/explain.py +0 -47
  24. driftwatch_cli-3.0.0/drift_engine/models.py +0 -42
  25. driftwatch_cli-3.0.0/drift_engine/remediation.py +0 -193
  26. driftwatch_cli-3.0.0/drift_engine/tf_parser.py +0 -40
  27. driftwatch_cli-3.0.0/driftwatch/cli.py +0 -156
  28. driftwatch_cli-3.0.0/driftwatch_cli.egg-info/PKG-INFO +0 -13
  29. driftwatch_cli-3.0.0/driftwatch_cli.egg-info/requires.txt +0 -6
  30. driftwatch_cli-3.0.0/pyproject.toml +0 -23
  31. driftwatch_cli-3.0.0/tests/test_diff_engine.py +0 -39
  32. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/LICENSE +0 -0
  33. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/drift_engine/__init__.py +0 -0
  34. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/driftwatch/__init__.py +0 -0
  35. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/driftwatch_cli.egg-info/dependency_links.txt +0 -0
  36. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/driftwatch_cli.egg-info/entry_points.txt +0 -0
  37. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/driftwatch_cli.egg-info/top_level.txt +0 -0
  38. {driftwatch_cli-3.0.0 → driftwatch_cli-3.0.2}/setup.cfg +0 -0
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.4
2
+ Name: driftwatch-cli
3
+ Version: 3.0.2
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
+ Dynamic: license-file
37
+
38
+ # DriftWatch 🛡️
39
+
40
+ **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.
41
+
42
+ ---
43
+
44
+ ## 🚀 Key Features
45
+
46
+ - **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.
47
+ - **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`.
48
+ - **AI-Powered Risk Summaries**: Integrates with LLMs to provide plain-English security analysis and compliance impact assessments.
49
+ - **Deterministic IaC Remediation**: Recommends safe, template-generated `terraform import` and `terraform apply` commands rather than hallucinated AI outputs.
50
+ - **Guarded Auto-Remediation**: Pre-flight validation checks for EC2 (EBS verification, Spot skip, running state), RDS maintenance-window defaults, and explicit interactive confirmations.
51
+ - **Multi-Channel Alerting**: Instant notifications via Telegram, Slack, and Email.
52
+ - **CI/CD Quality Gate**: Built-in GitHub Actions integration to enforce zero-tolerance drift policies in pull requests.
53
+
54
+ ---
55
+
56
+ ## 🏛️ Architecture Overview
57
+
58
+ ```
59
+ driftwatch/
60
+ ├── drift_engine/ # Core drift detection & reconciliation engine
61
+ │ ├── aws_client.py # Live AWS resource discovery (boto3)
62
+ │ ├── core.py # Diff evaluation & data-driven severity engine
63
+ │ ├── database.py # PostgreSQL scan history recorder
64
+ │ ├── explain.py # AI risk summaries & deterministic IaC templates
65
+ │ ├── models.py # Data models & attribute severity tables
66
+ │ ├── notifications.py # Alert dispatcher (Telegram, Slack, Email)
67
+ │ ├── remediation.py # Guarded auto-remediation handlers
68
+ │ └── tf_parser.py # Terraform state JSON parser
69
+ ├── driftwatch/ # CLI Entrypoint (Typer)
70
+ │ └── cli.py # Command definitions: scan, explain, remediate
71
+ ├── terraform/ # Example infrastructure and state configuration
72
+ ├── kubernetes/ # Kubernetes CronJob deployment
73
+ └── tests/ # Comprehensive unit tests with moto AWS mocks
74
+ ```
75
+
76
+ ---
77
+
78
+ ## 📋 Prerequisites
79
+
80
+ - **Python**: `>= 3.10`
81
+ - **AWS Credentials**: Configured via environment variables, IAM roles, or AWS CLI credentials (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_DEFAULT_REGION`).
82
+ - **Terraform State File**: Local JSON state or remote state (`terraform.tfstate`).
83
+ - **PostgreSQL** *(Optional)*: For persistent scan audit history.
84
+ - **Groq API Key** *(Optional)*: `GROQ_API_KEY` for AI risk explanations.
85
+
86
+ ---
87
+
88
+ ## 📦 Installation
89
+
90
+ ### From PyPI (Recommended)
91
+ ```bash
92
+ pip install driftwatch-cli
93
+ ```
94
+
95
+ ### From Source (Local Development)
96
+ ```bash
97
+ git clone https://github.com/hastagnitin/driftwatch.git
98
+ cd driftwatch
99
+ pip install -e .[dev]
100
+ ```
101
+
102
+ ---
103
+
104
+ ## ⚙️ Configuration
105
+
106
+ Create a `.env` file in the root directory:
107
+
108
+ ```env
109
+ AWS_DEFAULT_REGION=ap-south-1
110
+ TF_STATE_PATH=terraform/terraform.tfstate
111
+
112
+ # Optional: AI Risk Summaries
113
+ GROQ_API_KEY=your_groq_api_key
114
+
115
+ # Optional: Notifications
116
+ SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
117
+ TELEGRAM_BOT_TOKEN=your_telegram_bot_token
118
+ TELEGRAM_CHAT_ID=your_telegram_chat_id
119
+
120
+ # Optional: PostgreSQL Database
121
+ DB_HOST=localhost
122
+ DB_PORT=5432
123
+ DB_NAME=driftwatch
124
+ DB_USER=postgres
125
+ DB_PASSWORD=your_db_password
126
+ ```
127
+
128
+ ---
129
+
130
+ ## 💻 Usage & CLI Commands
131
+
132
+ ### 1. Scan for Drift
133
+ Scan live AWS infrastructure against your Terraform state:
134
+ ```bash
135
+ # Basic scan
136
+ driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate
137
+
138
+ # Enforce CI Gate (fails build if CRITICAL drift is found)
139
+ driftwatch scan --region ap-south-1 --fail-on CRITICAL
140
+ ```
141
+
142
+ ### 2. Explain Drift
143
+ Generate AI risk analysis and deterministic IaC fix recommendations:
144
+ ```bash
145
+ driftwatch explain sg-0123456789abcdef0 --region ap-south-1
146
+ ```
147
+
148
+ ### 3. Remediate Drift
149
+ Safely remediate drifted resources back to IaC specifications:
150
+ ```bash
151
+ # Dry run mode (default)
152
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run
153
+
154
+ # Apply mode with interactive confirmation
155
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
156
+ ```
157
+
158
+ ---
159
+
160
+ ## ⚠️ Security & Safety Guidelines
161
+
162
+ > [!WARNING]
163
+ > **Auto-Remediation Safety**:
164
+ > - Automated drift remediation is intended for **Development** and **Staging** environments.
165
+ > - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and recommends template-generated `terraform apply` / `terraform import` workflows.
166
+ > - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to avoid unplanned reboots.
167
+
168
+ ---
169
+
170
+ ## 🧪 Testing
171
+
172
+ Run the test suite with test coverage:
173
+ ```bash
174
+ pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
175
+ ```
176
+
177
+ ---
178
+
179
+ ## 📄 License
180
+
181
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,144 @@
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 PyPI (Recommended)
54
+ ```bash
55
+ pip install driftwatch-cli
56
+ ```
57
+
58
+ ### From Source (Local Development)
59
+ ```bash
60
+ git clone https://github.com/hastagnitin/driftwatch.git
61
+ cd driftwatch
62
+ pip install -e .[dev]
63
+ ```
64
+
65
+ ---
66
+
67
+ ## ⚙️ Configuration
68
+
69
+ Create a `.env` file in the root directory:
70
+
71
+ ```env
72
+ AWS_DEFAULT_REGION=ap-south-1
73
+ TF_STATE_PATH=terraform/terraform.tfstate
74
+
75
+ # Optional: AI Risk Summaries
76
+ GROQ_API_KEY=your_groq_api_key
77
+
78
+ # Optional: Notifications
79
+ SLACK_WEBHOOK_URL=https://hooks.slack.com/services/...
80
+ TELEGRAM_BOT_TOKEN=your_telegram_bot_token
81
+ TELEGRAM_CHAT_ID=your_telegram_chat_id
82
+
83
+ # Optional: PostgreSQL Database
84
+ DB_HOST=localhost
85
+ DB_PORT=5432
86
+ DB_NAME=driftwatch
87
+ DB_USER=postgres
88
+ DB_PASSWORD=your_db_password
89
+ ```
90
+
91
+ ---
92
+
93
+ ## 💻 Usage & CLI Commands
94
+
95
+ ### 1. Scan for Drift
96
+ Scan live AWS infrastructure against your Terraform state:
97
+ ```bash
98
+ # Basic scan
99
+ driftwatch scan --region ap-south-1 --state terraform/terraform.tfstate
100
+
101
+ # Enforce CI Gate (fails build if CRITICAL drift is found)
102
+ driftwatch scan --region ap-south-1 --fail-on CRITICAL
103
+ ```
104
+
105
+ ### 2. Explain Drift
106
+ Generate AI risk analysis and deterministic IaC fix recommendations:
107
+ ```bash
108
+ driftwatch explain sg-0123456789abcdef0 --region ap-south-1
109
+ ```
110
+
111
+ ### 3. Remediate Drift
112
+ Safely remediate drifted resources back to IaC specifications:
113
+ ```bash
114
+ # Dry run mode (default)
115
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --dry-run
116
+
117
+ # Apply mode with interactive confirmation
118
+ driftwatch remediate sg-0123456789abcdef0 --region ap-south-1 --apply
119
+ ```
120
+
121
+ ---
122
+
123
+ ## ⚠️ Security & Safety Guidelines
124
+
125
+ > [!WARNING]
126
+ > **Auto-Remediation Safety**:
127
+ > - Automated drift remediation is intended for **Development** and **Staging** environments.
128
+ > - In **Production**, DriftWatch enforces manual confirmation prompts (`confirm_action()`) and recommends template-generated `terraform apply` / `terraform import` workflows.
129
+ > - RDS modifications default to maintenance windows (`ApplyImmediately=False`) to avoid unplanned reboots.
130
+
131
+ ---
132
+
133
+ ## 🧪 Testing
134
+
135
+ Run the test suite with test coverage:
136
+ ```bash
137
+ pytest tests/ -v --cov=drift_engine --cov=driftwatch --cov-report=term-missing
138
+ ```
139
+
140
+ ---
141
+
142
+ ## 📄 License
143
+
144
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -1,41 +1,59 @@
1
+ import os
2
+ import sys
1
3
  import boto3
2
4
  from datetime import datetime, timedelta
3
5
 
4
- def fetch_live_ec2_instances(region: str) -> dict:
5
- ec2 = boto3.client("ec2", region_name=region)
6
+ def get_boto3_session(profile: str = None, region: str = None) -> boto3.Session:
7
+ actual_profile = profile or os.environ.get("AWS_PROFILE")
8
+ actual_region = region or os.environ.get("AWS_DEFAULT_REGION")
9
+ if actual_profile:
10
+ return boto3.Session(profile_name=actual_profile, region_name=actual_region)
11
+ return boto3.Session(region_name=actual_region)
12
+
13
+ def get_boto3_client(service_name: str, profile: str = None, region: str = None):
14
+ session = get_boto3_session(profile=profile, region=region)
15
+ return session.client(service_name, region_name=region or session.region_name)
16
+
17
+ def fetch_live_ec2_instances(region: str, profile: str = None) -> dict:
18
+ ec2 = get_boto3_client("ec2", profile=profile, region=region)
6
19
  live = {}
7
- paginator = ec2.get_paginator("describe_instances")
8
-
9
- for page in paginator.paginate():
10
- for reservation in page["Reservations"]:
11
- for instance in reservation["Instances"]:
12
- if instance["State"]["Name"] == "terminated":
13
- continue
14
-
15
- tags_list = instance.get("Tags", [])
16
- tags_dict = {t["Key"]: t["Value"] for t in tags_list}
17
- name = tags_dict.get("Name", "Unknown")
18
-
19
- sg_ids = []
20
- for sg in instance.get("SecurityGroups", []):
21
- sg_ids.append(sg.get("GroupId"))
22
- sg_ids.sort()
23
-
24
- live[instance["InstanceId"]] = {
25
- "type": "aws_instance",
26
- "name": name,
27
- "attributes": {
28
- "id": instance["InstanceId"],
29
- "instance_type": instance["InstanceType"],
30
- "ami": instance["ImageId"],
31
- "tags": tags_dict,
32
- "vpc_security_group_ids": sg_ids
33
- },
34
- }
20
+ try:
21
+ paginator = ec2.get_paginator("describe_instances")
22
+ for page in paginator.paginate():
23
+ for reservation in page.get("Reservations", []):
24
+ for instance in reservation.get("Instances", []):
25
+ if instance.get("State", {}).get("Name") == "terminated":
26
+ continue
27
+
28
+ tags_list = instance.get("Tags", [])
29
+ tags_dict = {t["Key"]: t["Value"] for t in tags_list if "Key" in t and "Value" in t}
30
+ name = tags_dict.get("Name", "Unknown")
31
+
32
+ sg_ids = []
33
+ for sg in instance.get("SecurityGroups", []):
34
+ if "GroupId" in sg:
35
+ sg_ids.append(sg.get("GroupId"))
36
+ sg_ids.sort()
37
+
38
+ instance_id = instance["InstanceId"]
39
+ live[instance_id] = {
40
+ "type": "aws_instance",
41
+ "name": name,
42
+ "attributes": {
43
+ "id": instance_id,
44
+ "instance_type": instance.get("InstanceType"),
45
+ "ami": instance.get("ImageId"),
46
+ "tags": tags_dict,
47
+ "vpc_security_group_ids": sg_ids
48
+ },
49
+ }
50
+ except Exception as e:
51
+ print(f"Failed to fetch aws_instance: {e}", file=sys.stderr)
52
+ return None
35
53
  return live
36
54
 
37
- def fetch_live_s3_buckets(region: str) -> dict:
38
- s3 = boto3.client("s3", region_name=region)
55
+ def fetch_live_s3_buckets(region: str, profile: str = None) -> dict:
56
+ s3 = get_boto3_client("s3", profile=profile, region=region)
39
57
  live = {}
40
58
  try:
41
59
  response = s3.list_buckets()
@@ -44,7 +62,7 @@ def fetch_live_s3_buckets(region: str) -> dict:
44
62
  try:
45
63
  tags_response = s3.get_bucket_tagging(Bucket=bucket_name)
46
64
  tags_list = tags_response.get("TagSet", [])
47
- tags_dict = {t["Key"]: t["Value"] for t in tags_list}
65
+ tags_dict = {t["Key"]: t["Value"] for t in tags_list if "Key" in t and "Value" in t}
48
66
  name = tags_dict.get("Name", bucket_name)
49
67
  except Exception:
50
68
  tags_dict = {}
@@ -60,22 +78,22 @@ def fetch_live_s3_buckets(region: str) -> dict:
60
78
  },
61
79
  }
62
80
  except Exception as e:
63
- pass
81
+ print(f"Failed to fetch aws_s3_bucket: {e}", file=sys.stderr)
82
+ return None
64
83
  return live
65
84
 
66
- def fetch_live_security_groups(region: str) -> dict:
67
- ec2 = boto3.client("ec2", region_name=region)
85
+ def fetch_live_security_groups(region: str, profile: str = None) -> dict:
86
+ ec2 = get_boto3_client("ec2", profile=profile, region=region)
68
87
  live = {}
69
- paginator = ec2.get_paginator("describe_security_groups")
70
-
71
88
  try:
89
+ paginator = ec2.get_paginator("describe_security_groups")
72
90
  for page in paginator.paginate():
73
- for sg in page["SecurityGroups"]:
91
+ for sg in page.get("SecurityGroups", []):
74
92
  sg_id = sg["GroupId"]
75
- sg_name = sg["GroupName"]
93
+ sg_name = sg.get("GroupName", "")
76
94
 
77
95
  tags_list = sg.get("Tags", [])
78
- tags_dict = {t["Key"]: t["Value"] for t in tags_list}
96
+ tags_dict = {t["Key"]: t["Value"] for t in tags_list if "Key" in t and "Value" in t}
79
97
  name_tag = tags_dict.get("Name", sg_name)
80
98
 
81
99
  ingress_rules = []
@@ -113,25 +131,26 @@ def fetch_live_security_groups(region: str) -> dict:
113
131
  },
114
132
  }
115
133
  except Exception as e:
116
- pass
134
+ print(f"Failed to fetch aws_security_group: {e}", file=sys.stderr)
135
+ return None
117
136
  return live
118
137
 
119
- def fetch_live_rds_instances(region: str = "ap-south-1") -> dict:
120
- rds = boto3.client("rds", region_name=region)
138
+ def fetch_live_rds_instances(region: str, profile: str = None) -> dict:
139
+ rds = get_boto3_client("rds", profile=profile, region=region)
121
140
  live = {}
122
- paginator = rds.get_paginator("describe_db_instances")
123
141
  try:
142
+ paginator = rds.get_paginator("describe_db_instances")
124
143
  for page in paginator.paginate():
125
- for db in page["DBInstances"]:
126
- db_id = db.get("DbiResourceId")
127
- db_name = db["DBInstanceIdentifier"]
144
+ for db in page.get("DBInstances", []):
145
+ db_id = db.get("DBInstanceIdentifier")
128
146
  if not db_id:
129
147
  continue
130
148
  live[db_id] = {
131
149
  "type": "aws_db_instance",
132
- "name": db_name,
150
+ "name": db_id,
133
151
  "attributes": {
134
152
  "id": db_id,
153
+ "identifier": db_id,
135
154
  "allocated_storage": db.get("AllocatedStorage"),
136
155
  "engine": db.get("Engine"),
137
156
  "engine_version": db.get("EngineVersion"),
@@ -140,17 +159,20 @@ def fetch_live_rds_instances(region: str = "ap-south-1") -> dict:
140
159
  },
141
160
  }
142
161
  except Exception as e:
143
- pass
162
+ print(f"Failed to fetch aws_db_instance: {e}", file=sys.stderr)
163
+ return None
144
164
  return live
145
165
 
146
- def fetch_live_lambda_functions(region: str = "ap-south-1") -> dict:
147
- lambda_client = boto3.client("lambda", region_name=region)
166
+ def fetch_live_lambda_functions(region: str, profile: str = None) -> dict:
167
+ lambda_client = get_boto3_client("lambda", profile=profile, region=region)
148
168
  live = {}
149
- paginator = lambda_client.get_paginator("list_functions")
150
169
  try:
170
+ paginator = lambda_client.get_paginator("list_functions")
151
171
  for page in paginator.paginate():
152
- for func in page["Functions"]:
153
- func_name = func["FunctionName"]
172
+ for func in page.get("Functions", []):
173
+ func_name = func.get("FunctionName")
174
+ if not func_name:
175
+ continue
154
176
  live[func_name] = {
155
177
  "type": "aws_lambda_function",
156
178
  "name": func_name,
@@ -165,35 +187,50 @@ def fetch_live_lambda_functions(region: str = "ap-south-1") -> dict:
165
187
  },
166
188
  }
167
189
  except Exception as e:
168
- pass
190
+ print(f"Failed to fetch aws_lambda_function: {e}", file=sys.stderr)
191
+ return None
169
192
  return live
170
193
 
171
- def fetch_live_iam_roles(region: str = "ap-south-1") -> dict:
172
- iam = boto3.client("iam", region_name=region)
194
+ def fetch_live_iam_roles(region: str, profile: str = None) -> dict:
195
+ iam = get_boto3_client("iam", profile=profile, region=region)
173
196
  live = {}
174
197
  try:
175
198
  paginator = iam.get_paginator("list_roles")
176
199
  for page in paginator.paginate():
177
- for role in page["Roles"]:
178
- role_name = role["RoleName"]
200
+ for role in page.get("Roles", []):
201
+ role_name = role.get("RoleName")
202
+ if not role_name:
203
+ continue
179
204
  if role_name.startswith("AWSServiceRoleFor") or role.get("Path", "").startswith("/aws-service-role/"):
180
205
  continue
206
+
207
+ try:
208
+ policies = iam.list_attached_role_policies(RoleName=role_name)
209
+ attached_policies = sorted(
210
+ p["PolicyArn"] for p in policies.get("AttachedPolicies", []) if "PolicyArn" in p
211
+ )
212
+ except Exception:
213
+ attached_policies = []
214
+
181
215
  live[role_name] = {
182
216
  "type": "aws_iam_role",
183
217
  "name": role_name,
184
218
  "attributes": {
185
219
  "id": role_name,
186
220
  "name": role_name,
187
- "arn": role["Arn"]
221
+ "path": role.get("Path", "/"),
222
+ "arn": role.get("Arn", ""),
223
+ "attached_policies": attached_policies
188
224
  }
189
225
  }
190
226
  except Exception as e:
191
- pass
227
+ print(f"Failed to fetch aws_iam_role: {e}", file=sys.stderr)
228
+ return None
192
229
  return live
193
230
 
194
- def get_resource_cost(resource_id: str) -> float:
231
+ def get_resource_cost(resource_id: str, profile: str = None) -> float | None:
195
232
  try:
196
- client = boto3.client("ce", region_name="us-east-1")
233
+ client = get_boto3_client("ce", profile=profile, region="us-east-1")
197
234
 
198
235
  end_date = datetime.today().strftime("%Y-%m-%d")
199
236
  start_date = (datetime.today() - timedelta(days=30)).strftime("%Y-%m-%d")
@@ -210,8 +247,10 @@ def get_resource_cost(resource_id: str) -> float:
210
247
  }
211
248
  )
212
249
 
213
- usd_cost = float(response["ResultsByTime"][0]["Total"]["UnblendedCost"]["Amount"])
214
- inr_cost = round(usd_cost * 83.5, 2)
215
- return inr_cost
250
+ results_by_time = response.get("ResultsByTime", [])
251
+ if not results_by_time:
252
+ return None
253
+ usd_cost = float(results_by_time[0]["Total"]["UnblendedCost"]["Amount"])
254
+ return usd_cost
216
255
  except Exception:
217
- return 0.0
256
+ return None