cloudg 0.3.0__py3-none-any.whl
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.
- cloudg/__init__.py +21 -0
- cloudg/api.py +613 -0
- cloudg/cli.py +934 -0
- cloudg/collectors/__init__.py +5 -0
- cloudg/collectors/aws.py +830 -0
- cloudg/collectors/azure.py +362 -0
- cloudg/collectors/base.py +44 -0
- cloudg/collectors/gcp.py +170 -0
- cloudg/collectors/multi.py +329 -0
- cloudg/config.py +261 -0
- cloudg/coverage.py +93 -0
- cloudg/credentials.py +451 -0
- cloudg/graph/__init__.py +6 -0
- cloudg/graph/builder.py +336 -0
- cloudg/graph/ontology.py +914 -0
- cloudg/graph/rag_export.py +533 -0
- cloudg/graph/reachability.py +237 -0
- cloudg/normaliser.py +390 -0
- cloudg/policies/custodian-aws-security.yml +139 -0
- cloudg/policies/custodian-azure.yml +95 -0
- cloudg/policies/custodian-gcp.yml +87 -0
- cloudg/policies/custodian.yml +131 -0
- cloudg/region_discovery.py +330 -0
- cloudg/registry.py +142 -0
- cloudg/renderers/__init__.py +1 -0
- cloudg/renderers/html_report.py +430 -0
- cloudg/renderers/json_export.py +65 -0
- cloudg/renderers/svg.py +689 -0
- cloudg/renderers/terraform_export.py +666 -0
- cloudg/retry.py +103 -0
- cloudg/rules/cis_aws_v3.yaml +148 -0
- cloudg/rules/cis_azure_v2.yaml +142 -0
- cloudg/rules/cis_gcp_v3.yaml +133 -0
- cloudg/rules/frameworks/aws_foundational_security_best_practices_aws.yaml +1286 -0
- cloudg/rules/frameworks/cis_5.0_aws.yaml +280 -0
- cloudg/rules/frameworks/cis_5.0_azure.yaml +475 -0
- cloudg/rules/frameworks/cis_5.0_gcp.yaml +327 -0
- cloudg/rules/frameworks/gdpr_aws.yaml +95 -0
- cloudg/rules/frameworks/hipaa_aws.yaml +461 -0
- cloudg/rules/frameworks/hipaa_azure.yaml +504 -0
- cloudg/rules/frameworks/hipaa_gcp.yaml +211 -0
- cloudg/rules/frameworks/iso27001_2022_aws.yaml +789 -0
- cloudg/rules/frameworks/iso27001_2022_azure.yaml +477 -0
- cloudg/rules/frameworks/iso27001_2022_gcp.yaml +240 -0
- cloudg/rules/frameworks/mitre_attack_aws.yaml +596 -0
- cloudg/rules/frameworks/mitre_attack_azure.yaml +418 -0
- cloudg/rules/frameworks/mitre_attack_gcp.yaml +300 -0
- cloudg/rules/frameworks/nist_800_53_revision_5_aws.yaml +3234 -0
- cloudg/rules/frameworks/nist_csf_2.0_aws.yaml +828 -0
- cloudg/rules/frameworks/pci_4.0_aws.yaml +7108 -0
- cloudg/rules/frameworks/pci_4.0_azure.yaml +4696 -0
- cloudg/rules/frameworks/pci_4.0_gcp.yaml +5405 -0
- cloudg/rules/frameworks/soc2_aws.yaml +421 -0
- cloudg/rules/frameworks/soc2_azure.yaml +477 -0
- cloudg/rules/frameworks/soc2_gcp.yaml +342 -0
- cloudg/rules/gdpr.yaml +56 -0
- cloudg/rules/hipaa_security_rule.yaml +83 -0
- cloudg/rules/iso_27001_2022.yaml +88 -0
- cloudg/rules/nist_800_53.yaml +134 -0
- cloudg/rules/pci_dss_v4.yaml +108 -0
- cloudg/rules/soc2_tsc.yaml +93 -0
- cloudg/scanners/__init__.py +1 -0
- cloudg/scanners/checkov.py +174 -0
- cloudg/scanners/iam_linter.py +200 -0
- cloudg/scanners/prowler.py +237 -0
- cloudg/scanners/scoutsuite.py +163 -0
- cloudg/scanners/trivy.py +339 -0
- cloudg/schema/__init__.py +25 -0
- cloudg/schema/models.py +260 -0
- cloudg/templates/report.html.j2 +828 -0
- cloudg-0.3.0.dist-info/METADATA +330 -0
- cloudg-0.3.0.dist-info/RECORD +75 -0
- cloudg-0.3.0.dist-info/WHEEL +4 -0
- cloudg-0.3.0.dist-info/entry_points.txt +14 -0
- cloudg-0.3.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
"""Terraform .tf.json recreation support.
|
|
2
|
+
|
|
3
|
+
Generates Terraform-native JSON configuration from collected CloudG
|
|
4
|
+
assets, enabling infrastructure recreation and state import.
|
|
5
|
+
|
|
6
|
+
Output structure:
|
|
7
|
+
reports/terraform/
|
|
8
|
+
├── provider.tf.json
|
|
9
|
+
├── variables.tf.json
|
|
10
|
+
├── main.tf.json
|
|
11
|
+
└── import_commands.sh
|
|
12
|
+
|
|
13
|
+
Uses .tf.json format (not HCL) because Terraform natively reads JSON
|
|
14
|
+
and it's trivially safe to generate from Python dicts.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import logging
|
|
21
|
+
import re
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from cloudg.schema.models import (
|
|
26
|
+
AssetType,
|
|
27
|
+
CloudAsset,
|
|
28
|
+
CloudProvider,
|
|
29
|
+
NetworkEdge,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
logger = logging.getLogger(__name__)
|
|
33
|
+
|
|
34
|
+
# ---------------------------------------------------------------------------
|
|
35
|
+
# Asset Type → Terraform resource mapping
|
|
36
|
+
# ---------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
# Each entry: (terraform_resource_type, attribute_transformer_function_name)
|
|
39
|
+
_TF_RESOURCE_MAP: dict[AssetType, str] = {
|
|
40
|
+
# AWS
|
|
41
|
+
AssetType.EC2: "aws_instance",
|
|
42
|
+
AssetType.VPC: "aws_vpc",
|
|
43
|
+
AssetType.SUBNET: "aws_subnet",
|
|
44
|
+
AssetType.SECURITY_GROUP: "aws_security_group",
|
|
45
|
+
AssetType.S3_BUCKET: "aws_s3_bucket",
|
|
46
|
+
AssetType.RDS_INSTANCE: "aws_db_instance",
|
|
47
|
+
AssetType.LAMBDA_FUNCTION: "aws_lambda_function",
|
|
48
|
+
AssetType.LOAD_BALANCER: "aws_lb",
|
|
49
|
+
AssetType.IAM_ROLE: "aws_iam_role",
|
|
50
|
+
AssetType.IAM_USER: "aws_iam_user",
|
|
51
|
+
AssetType.IAM_POLICY: "aws_iam_policy",
|
|
52
|
+
AssetType.ECS_CLUSTER: "aws_ecs_cluster",
|
|
53
|
+
AssetType.DYNAMODB_TABLE: "aws_dynamodb_table",
|
|
54
|
+
AssetType.KMS_KEY: "aws_kms_key",
|
|
55
|
+
AssetType.SECRET: "aws_secretsmanager_secret",
|
|
56
|
+
AssetType.CLOUDFRONT: "aws_cloudfront_distribution",
|
|
57
|
+
AssetType.NAT_GATEWAY: "aws_nat_gateway",
|
|
58
|
+
AssetType.INTERNET_GATEWAY: "aws_internet_gateway",
|
|
59
|
+
AssetType.ELASTIC_IP: "aws_eip",
|
|
60
|
+
AssetType.ROUTE_TABLE: "aws_route_table",
|
|
61
|
+
AssetType.NACL: "aws_network_acl",
|
|
62
|
+
AssetType.CLOUDTRAIL: "aws_cloudtrail",
|
|
63
|
+
# Azure
|
|
64
|
+
AssetType.VIRTUAL_MACHINE: "azurerm_linux_virtual_machine",
|
|
65
|
+
AssetType.VNET: "azurerm_virtual_network",
|
|
66
|
+
AssetType.NSG: "azurerm_network_security_group",
|
|
67
|
+
AssetType.BLOB_STORAGE: "azurerm_storage_account",
|
|
68
|
+
AssetType.AZURE_SQL: "azurerm_mssql_database",
|
|
69
|
+
AssetType.KEY_VAULT: "azurerm_key_vault",
|
|
70
|
+
AssetType.AKS_CLUSTER: "azurerm_kubernetes_cluster",
|
|
71
|
+
AssetType.APP_SERVICE: "azurerm_linux_web_app",
|
|
72
|
+
# GCP
|
|
73
|
+
AssetType.GCE_INSTANCE: "google_compute_instance",
|
|
74
|
+
AssetType.GCS_BUCKET: "google_storage_bucket",
|
|
75
|
+
AssetType.CLOUD_SQL: "google_sql_database_instance",
|
|
76
|
+
AssetType.CLOUD_FUNCTION: "google_cloudfunctions_function",
|
|
77
|
+
AssetType.GKE_CLUSTER: "google_container_cluster",
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
# Read-only / computed fields to strip from Terraform output
|
|
81
|
+
_COMPUTED_FIELDS = {
|
|
82
|
+
"arn",
|
|
83
|
+
"id",
|
|
84
|
+
"state",
|
|
85
|
+
"status",
|
|
86
|
+
"create_date",
|
|
87
|
+
"creation_date",
|
|
88
|
+
"public_ip",
|
|
89
|
+
"private_ip",
|
|
90
|
+
"dns_name",
|
|
91
|
+
"domain_name",
|
|
92
|
+
"last_modified",
|
|
93
|
+
"last_accessed",
|
|
94
|
+
"last_rotated",
|
|
95
|
+
"running_tasks",
|
|
96
|
+
"active_services",
|
|
97
|
+
"item_count",
|
|
98
|
+
"size_bytes",
|
|
99
|
+
"acl_grants",
|
|
100
|
+
"public_access_block",
|
|
101
|
+
"key_state",
|
|
102
|
+
"origin",
|
|
103
|
+
"image_id",
|
|
104
|
+
"password_last_used",
|
|
105
|
+
"user_id",
|
|
106
|
+
"role_id",
|
|
107
|
+
"web_acl_id",
|
|
108
|
+
"capacity_providers",
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _sanitise_tf_name(name: str) -> str:
|
|
113
|
+
"""Convert a resource name to a valid Terraform resource label."""
|
|
114
|
+
# Replace non-alphanumeric with underscore, strip leading digits
|
|
115
|
+
clean = re.sub(r"[^a-zA-Z0-9_]", "_", name)
|
|
116
|
+
clean = re.sub(r"^[0-9]+", "", clean)
|
|
117
|
+
clean = re.sub(r"_+", "_", clean).strip("_")
|
|
118
|
+
return clean[:64] or "resource"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _get_import_id(asset: CloudAsset) -> str:
|
|
122
|
+
"""Determine the best ID for `terraform import` command."""
|
|
123
|
+
if asset.arn:
|
|
124
|
+
return asset.arn
|
|
125
|
+
# Fallback to provider-specific IDs from metadata
|
|
126
|
+
for key in ("vpc_id", "subnet_id", "group_id", "instance_id"):
|
|
127
|
+
val = asset.metadata.get(key)
|
|
128
|
+
if val:
|
|
129
|
+
return val
|
|
130
|
+
return asset.id
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
# ---------------------------------------------------------------------------
|
|
134
|
+
# Per-resource attribute transformers
|
|
135
|
+
# ---------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _transform_ec2(asset: CloudAsset) -> dict[str, Any]:
|
|
139
|
+
"""Transform EC2 instance to aws_instance attributes."""
|
|
140
|
+
m = asset.metadata
|
|
141
|
+
attrs: dict[str, Any] = {}
|
|
142
|
+
if m.get("instance_type"):
|
|
143
|
+
attrs["instance_type"] = m["instance_type"]
|
|
144
|
+
if m.get("image_id"):
|
|
145
|
+
attrs["ami"] = m["image_id"]
|
|
146
|
+
if m.get("subnet_id"):
|
|
147
|
+
attrs["subnet_id"] = m["subnet_id"]
|
|
148
|
+
if m.get("security_groups"):
|
|
149
|
+
attrs["vpc_security_group_ids"] = m["security_groups"]
|
|
150
|
+
if asset.tags:
|
|
151
|
+
attrs["tags"] = asset.tags
|
|
152
|
+
return attrs
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _transform_vpc(asset: CloudAsset) -> dict[str, Any]:
|
|
156
|
+
m = asset.metadata
|
|
157
|
+
attrs: dict[str, Any] = {}
|
|
158
|
+
if m.get("cidr_block"):
|
|
159
|
+
attrs["cidr_block"] = m["cidr_block"]
|
|
160
|
+
attrs["enable_dns_support"] = True
|
|
161
|
+
attrs["enable_dns_hostnames"] = True
|
|
162
|
+
if asset.tags:
|
|
163
|
+
attrs["tags"] = asset.tags
|
|
164
|
+
return attrs
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _transform_subnet(asset: CloudAsset) -> dict[str, Any]:
|
|
168
|
+
m = asset.metadata
|
|
169
|
+
attrs: dict[str, Any] = {}
|
|
170
|
+
if m.get("vpc_id"):
|
|
171
|
+
attrs["vpc_id"] = m["vpc_id"]
|
|
172
|
+
if m.get("cidr_block"):
|
|
173
|
+
attrs["cidr_block"] = m["cidr_block"]
|
|
174
|
+
if m.get("availability_zone"):
|
|
175
|
+
attrs["availability_zone"] = m["availability_zone"]
|
|
176
|
+
if m.get("map_public_ip"):
|
|
177
|
+
attrs["map_public_ip_on_launch"] = m["map_public_ip"]
|
|
178
|
+
if asset.tags:
|
|
179
|
+
attrs["tags"] = asset.tags
|
|
180
|
+
return attrs
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _transform_security_group(asset: CloudAsset) -> dict[str, Any]:
|
|
184
|
+
m = asset.metadata
|
|
185
|
+
attrs: dict[str, Any] = {
|
|
186
|
+
"name": asset.name,
|
|
187
|
+
}
|
|
188
|
+
if m.get("description"):
|
|
189
|
+
attrs["description"] = m["description"]
|
|
190
|
+
if m.get("vpc_id"):
|
|
191
|
+
attrs["vpc_id"] = m["vpc_id"]
|
|
192
|
+
|
|
193
|
+
# Expand ingress rules
|
|
194
|
+
ingress_rules = []
|
|
195
|
+
for rule in m.get("ingress_rules", []):
|
|
196
|
+
for ip_range in rule.get("IpRanges", []):
|
|
197
|
+
proto = rule.get("IpProtocol", "-1")
|
|
198
|
+
ingress_rules.append(
|
|
199
|
+
{
|
|
200
|
+
"from_port": rule.get("FromPort", 0),
|
|
201
|
+
"to_port": rule.get("ToPort", 0),
|
|
202
|
+
"protocol": "all" if proto == "-1" else proto,
|
|
203
|
+
"cidr_blocks": [ip_range.get("CidrIp", "")],
|
|
204
|
+
"description": ip_range.get("Description", ""),
|
|
205
|
+
}
|
|
206
|
+
)
|
|
207
|
+
if ingress_rules:
|
|
208
|
+
attrs["ingress"] = ingress_rules
|
|
209
|
+
|
|
210
|
+
# Expand egress rules
|
|
211
|
+
egress_rules = []
|
|
212
|
+
for rule in m.get("egress_rules", []):
|
|
213
|
+
for ip_range in rule.get("IpRanges", []):
|
|
214
|
+
proto = rule.get("IpProtocol", "-1")
|
|
215
|
+
egress_rules.append(
|
|
216
|
+
{
|
|
217
|
+
"from_port": rule.get("FromPort", 0),
|
|
218
|
+
"to_port": rule.get("ToPort", 0),
|
|
219
|
+
"protocol": "all" if proto == "-1" else proto,
|
|
220
|
+
"cidr_blocks": [ip_range.get("CidrIp", "")],
|
|
221
|
+
"description": ip_range.get("Description", ""),
|
|
222
|
+
}
|
|
223
|
+
)
|
|
224
|
+
if egress_rules:
|
|
225
|
+
attrs["egress"] = egress_rules
|
|
226
|
+
|
|
227
|
+
if asset.tags:
|
|
228
|
+
attrs["tags"] = asset.tags
|
|
229
|
+
return attrs
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _transform_s3(asset: CloudAsset) -> dict[str, Any]:
|
|
233
|
+
attrs: dict[str, Any] = {
|
|
234
|
+
"bucket": asset.name,
|
|
235
|
+
}
|
|
236
|
+
if asset.tags:
|
|
237
|
+
attrs["tags"] = asset.tags
|
|
238
|
+
return attrs
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _transform_rds(asset: CloudAsset) -> dict[str, Any]:
|
|
242
|
+
m = asset.metadata
|
|
243
|
+
attrs: dict[str, Any] = {
|
|
244
|
+
"identifier": asset.name,
|
|
245
|
+
}
|
|
246
|
+
if m.get("engine"):
|
|
247
|
+
attrs["engine"] = m["engine"]
|
|
248
|
+
if m.get("engine_version"):
|
|
249
|
+
attrs["engine_version"] = m["engine_version"]
|
|
250
|
+
if m.get("instance_class"):
|
|
251
|
+
attrs["instance_class"] = m["instance_class"]
|
|
252
|
+
if m.get("storage_encrypted") is not None:
|
|
253
|
+
attrs["storage_encrypted"] = m["storage_encrypted"]
|
|
254
|
+
if m.get("multi_az") is not None:
|
|
255
|
+
attrs["multi_az"] = m["multi_az"]
|
|
256
|
+
if m.get("publicly_accessible") is not None:
|
|
257
|
+
attrs["publicly_accessible"] = m["publicly_accessible"]
|
|
258
|
+
return attrs
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _transform_lambda(asset: CloudAsset) -> dict[str, Any]:
|
|
262
|
+
m = asset.metadata
|
|
263
|
+
attrs: dict[str, Any] = {
|
|
264
|
+
"function_name": asset.name,
|
|
265
|
+
}
|
|
266
|
+
if m.get("runtime"):
|
|
267
|
+
attrs["runtime"] = m["runtime"]
|
|
268
|
+
if m.get("handler"):
|
|
269
|
+
attrs["handler"] = m["handler"]
|
|
270
|
+
if m.get("memory_size"):
|
|
271
|
+
attrs["memory_size"] = m["memory_size"]
|
|
272
|
+
if m.get("timeout"):
|
|
273
|
+
attrs["timeout"] = m["timeout"]
|
|
274
|
+
# Lambda needs a deployment package placeholder
|
|
275
|
+
attrs["filename"] = "lambda_placeholder.zip"
|
|
276
|
+
attrs["source_code_hash"] = ""
|
|
277
|
+
return attrs
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _transform_lb(asset: CloudAsset) -> dict[str, Any]:
|
|
281
|
+
m = asset.metadata
|
|
282
|
+
attrs: dict[str, Any] = {
|
|
283
|
+
"name": asset.name,
|
|
284
|
+
}
|
|
285
|
+
if m.get("type"):
|
|
286
|
+
attrs["load_balancer_type"] = m["type"].lower()
|
|
287
|
+
if m.get("scheme"):
|
|
288
|
+
attrs["internal"] = m["scheme"] == "internal"
|
|
289
|
+
if m.get("security_groups"):
|
|
290
|
+
attrs["security_groups"] = m["security_groups"]
|
|
291
|
+
if asset.tags:
|
|
292
|
+
attrs["tags"] = asset.tags
|
|
293
|
+
return attrs
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _transform_iam_role(asset: CloudAsset) -> dict[str, Any]:
|
|
297
|
+
m = asset.metadata
|
|
298
|
+
attrs: dict[str, Any] = {
|
|
299
|
+
"name": asset.name,
|
|
300
|
+
}
|
|
301
|
+
if m.get("assume_role_policy"):
|
|
302
|
+
policy = m["assume_role_policy"]
|
|
303
|
+
if isinstance(policy, dict):
|
|
304
|
+
attrs["assume_role_policy"] = json.dumps(policy)
|
|
305
|
+
else:
|
|
306
|
+
attrs["assume_role_policy"] = str(policy)
|
|
307
|
+
if m.get("max_session_duration"):
|
|
308
|
+
attrs["max_session_duration"] = m["max_session_duration"]
|
|
309
|
+
if asset.tags:
|
|
310
|
+
attrs["tags"] = asset.tags
|
|
311
|
+
return attrs
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _transform_iam_user(asset: CloudAsset) -> dict[str, Any]:
|
|
315
|
+
return {"name": asset.name}
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _transform_ecs_cluster(asset: CloudAsset) -> dict[str, Any]:
|
|
319
|
+
return {"name": asset.name}
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _transform_dynamodb(asset: CloudAsset) -> dict[str, Any]:
|
|
323
|
+
m = asset.metadata
|
|
324
|
+
attrs: dict[str, Any] = {
|
|
325
|
+
"name": asset.name,
|
|
326
|
+
}
|
|
327
|
+
if m.get("billing_mode"):
|
|
328
|
+
attrs["billing_mode"] = m["billing_mode"]
|
|
329
|
+
# DynamoDB needs at least a hash key — use placeholder if not known
|
|
330
|
+
attrs["hash_key"] = "id"
|
|
331
|
+
attrs["attribute"] = [{"name": "id", "type": "S"}]
|
|
332
|
+
return attrs
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _transform_kms(asset: CloudAsset) -> dict[str, Any]:
|
|
336
|
+
m = asset.metadata
|
|
337
|
+
attrs: dict[str, Any] = {}
|
|
338
|
+
if m.get("key_usage"):
|
|
339
|
+
attrs["key_usage"] = m["key_usage"]
|
|
340
|
+
if m.get("rotation_enabled"):
|
|
341
|
+
attrs["enable_key_rotation"] = m["rotation_enabled"]
|
|
342
|
+
attrs["description"] = f"KMS key {asset.name}"
|
|
343
|
+
return attrs
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _transform_secret(asset: CloudAsset) -> dict[str, Any]:
|
|
347
|
+
m = asset.metadata
|
|
348
|
+
attrs: dict[str, Any] = {
|
|
349
|
+
"name": asset.name,
|
|
350
|
+
}
|
|
351
|
+
if m.get("description"):
|
|
352
|
+
attrs["description"] = m["description"]
|
|
353
|
+
if m.get("kms_key_id"):
|
|
354
|
+
attrs["kms_key_id"] = m["kms_key_id"]
|
|
355
|
+
return attrs
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _transform_generic(asset: CloudAsset) -> dict[str, Any]:
|
|
359
|
+
"""Fallback transformer: strips computed fields from metadata."""
|
|
360
|
+
attrs: dict[str, Any] = {}
|
|
361
|
+
for key, value in asset.metadata.items():
|
|
362
|
+
if key.lower() not in _COMPUTED_FIELDS and value is not None:
|
|
363
|
+
attrs[key] = value
|
|
364
|
+
if asset.tags:
|
|
365
|
+
attrs["tags"] = asset.tags
|
|
366
|
+
return attrs
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
# Transformer registry
|
|
370
|
+
_TRANSFORMERS: dict[AssetType, Any] = {
|
|
371
|
+
AssetType.EC2: _transform_ec2,
|
|
372
|
+
AssetType.VPC: _transform_vpc,
|
|
373
|
+
AssetType.SUBNET: _transform_subnet,
|
|
374
|
+
AssetType.SECURITY_GROUP: _transform_security_group,
|
|
375
|
+
AssetType.S3_BUCKET: _transform_s3,
|
|
376
|
+
AssetType.RDS_INSTANCE: _transform_rds,
|
|
377
|
+
AssetType.LAMBDA_FUNCTION: _transform_lambda,
|
|
378
|
+
AssetType.LOAD_BALANCER: _transform_lb,
|
|
379
|
+
AssetType.IAM_ROLE: _transform_iam_role,
|
|
380
|
+
AssetType.IAM_USER: _transform_iam_user,
|
|
381
|
+
AssetType.ECS_CLUSTER: _transform_ecs_cluster,
|
|
382
|
+
AssetType.DYNAMODB_TABLE: _transform_dynamodb,
|
|
383
|
+
AssetType.KMS_KEY: _transform_kms,
|
|
384
|
+
AssetType.SECRET: _transform_secret,
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
# ---------------------------------------------------------------------------
|
|
389
|
+
# Terraform Exporter
|
|
390
|
+
# ---------------------------------------------------------------------------
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
class TerraformExporter:
|
|
394
|
+
"""Generates Terraform .tf.json from collected CloudG assets.
|
|
395
|
+
|
|
396
|
+
Produces:
|
|
397
|
+
- provider.tf.json — provider configuration
|
|
398
|
+
- variables.tf.json — parameterised values
|
|
399
|
+
- main.tf.json — all resource definitions
|
|
400
|
+
- import_commands.sh — terraform import commands for each resource
|
|
401
|
+
"""
|
|
402
|
+
|
|
403
|
+
def __init__(self, output_dir: str | Path = "./reports/terraform") -> None:
|
|
404
|
+
self._output_dir = Path(output_dir)
|
|
405
|
+
|
|
406
|
+
def export(
|
|
407
|
+
self,
|
|
408
|
+
assets: list[CloudAsset],
|
|
409
|
+
edges: list[NetworkEdge] | None = None,
|
|
410
|
+
) -> dict[str, Path]:
|
|
411
|
+
"""Generate all Terraform files from assets.
|
|
412
|
+
|
|
413
|
+
Args:
|
|
414
|
+
assets: Collected cloud assets.
|
|
415
|
+
edges: Optional edges for cross-reference resolution.
|
|
416
|
+
|
|
417
|
+
Returns:
|
|
418
|
+
Dict mapping file type → Path.
|
|
419
|
+
"""
|
|
420
|
+
self._output_dir.mkdir(parents=True, exist_ok=True)
|
|
421
|
+
|
|
422
|
+
# Determine providers used
|
|
423
|
+
providers_used = {a.provider for a in assets}
|
|
424
|
+
|
|
425
|
+
# Build cross-reference maps from edges
|
|
426
|
+
containment_map = self._build_containment_map(edges or [])
|
|
427
|
+
|
|
428
|
+
# Generate files
|
|
429
|
+
provider_path = self._generate_provider(providers_used, assets)
|
|
430
|
+
variables_path = self._generate_variables(assets)
|
|
431
|
+
main_path = self._generate_main(assets, containment_map)
|
|
432
|
+
import_path = self._generate_import_commands(assets)
|
|
433
|
+
|
|
434
|
+
paths = {
|
|
435
|
+
"provider": provider_path,
|
|
436
|
+
"variables": variables_path,
|
|
437
|
+
"main": main_path,
|
|
438
|
+
"import_commands": import_path,
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
logger.info(
|
|
442
|
+
"Terraform export complete: %d resources → %s",
|
|
443
|
+
len(assets),
|
|
444
|
+
self._output_dir,
|
|
445
|
+
)
|
|
446
|
+
return paths
|
|
447
|
+
|
|
448
|
+
def _build_containment_map(self, edges: list[NetworkEdge]) -> dict[str, str]:
|
|
449
|
+
"""Build a map of resource_id → container_id from CONTAINS edges."""
|
|
450
|
+
containment: dict[str, str] = {}
|
|
451
|
+
for edge in edges:
|
|
452
|
+
if edge.edge_type.value == "CONTAINS":
|
|
453
|
+
containment[edge.target_id] = edge.source_id
|
|
454
|
+
return containment
|
|
455
|
+
|
|
456
|
+
def _generate_provider(
|
|
457
|
+
self,
|
|
458
|
+
providers: set[CloudProvider],
|
|
459
|
+
assets: list[CloudAsset],
|
|
460
|
+
) -> Path:
|
|
461
|
+
"""Generate provider.tf.json."""
|
|
462
|
+
provider_blocks: dict[str, Any] = {}
|
|
463
|
+
|
|
464
|
+
if CloudProvider.AWS in providers:
|
|
465
|
+
provider_blocks["aws"] = {
|
|
466
|
+
"region": "${var.aws_region}",
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
if CloudProvider.AZURE in providers:
|
|
470
|
+
provider_blocks["azurerm"] = {
|
|
471
|
+
"features": {},
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
if CloudProvider.GCP in providers:
|
|
475
|
+
provider_blocks["google"] = {
|
|
476
|
+
"project": "${var.gcp_project_id}",
|
|
477
|
+
"region": "${var.gcp_region}",
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
tf_json = {
|
|
481
|
+
"terraform": {
|
|
482
|
+
"required_version": ">= 1.5.0",
|
|
483
|
+
"required_providers": {},
|
|
484
|
+
},
|
|
485
|
+
"provider": provider_blocks,
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
# Add required provider sources
|
|
489
|
+
if CloudProvider.AWS in providers:
|
|
490
|
+
tf_json["terraform"]["required_providers"]["aws"] = {
|
|
491
|
+
"source": "hashicorp/aws",
|
|
492
|
+
"version": "~> 5.0",
|
|
493
|
+
}
|
|
494
|
+
if CloudProvider.AZURE in providers:
|
|
495
|
+
tf_json["terraform"]["required_providers"]["azurerm"] = {
|
|
496
|
+
"source": "hashicorp/azurerm",
|
|
497
|
+
"version": "~> 3.0",
|
|
498
|
+
}
|
|
499
|
+
if CloudProvider.GCP in providers:
|
|
500
|
+
tf_json["terraform"]["required_providers"]["google"] = {
|
|
501
|
+
"source": "hashicorp/google",
|
|
502
|
+
"version": "~> 5.0",
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
path = self._output_dir / "provider.tf.json"
|
|
506
|
+
with open(path, "w") as f:
|
|
507
|
+
json.dump(tf_json, f, indent=2)
|
|
508
|
+
return path
|
|
509
|
+
|
|
510
|
+
def _generate_variables(self, assets: list[CloudAsset]) -> Path:
|
|
511
|
+
"""Generate variables.tf.json with parameterised values."""
|
|
512
|
+
regions = {a.region for a in assets if a.region and a.region != "global"}
|
|
513
|
+
accounts = {a.account_id for a in assets if a.account_id}
|
|
514
|
+
providers = {a.provider for a in assets}
|
|
515
|
+
|
|
516
|
+
variables: dict[str, Any] = {}
|
|
517
|
+
|
|
518
|
+
if CloudProvider.AWS in providers:
|
|
519
|
+
variables["aws_region"] = {
|
|
520
|
+
"description": "AWS region for resource deployment",
|
|
521
|
+
"type": "string",
|
|
522
|
+
"default": next(iter(regions), "us-east-1"),
|
|
523
|
+
}
|
|
524
|
+
if accounts:
|
|
525
|
+
variables["aws_account_id"] = {
|
|
526
|
+
"description": "AWS account ID",
|
|
527
|
+
"type": "string",
|
|
528
|
+
"default": next(iter(accounts), ""),
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
if CloudProvider.GCP in providers:
|
|
532
|
+
gcp_projects = {
|
|
533
|
+
a.account_id for a in assets if a.provider == CloudProvider.GCP and a.account_id
|
|
534
|
+
}
|
|
535
|
+
variables["gcp_project_id"] = {
|
|
536
|
+
"description": "GCP project ID",
|
|
537
|
+
"type": "string",
|
|
538
|
+
"default": next(iter(gcp_projects), ""),
|
|
539
|
+
}
|
|
540
|
+
variables["gcp_region"] = {
|
|
541
|
+
"description": "GCP region",
|
|
542
|
+
"type": "string",
|
|
543
|
+
"default": next(iter(regions), "us-central1"),
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
if CloudProvider.AZURE in providers:
|
|
547
|
+
azure_subs = {
|
|
548
|
+
a.account_id for a in assets if a.provider == CloudProvider.AZURE and a.account_id
|
|
549
|
+
}
|
|
550
|
+
variables["azure_subscription_id"] = {
|
|
551
|
+
"description": "Azure subscription ID",
|
|
552
|
+
"type": "string",
|
|
553
|
+
"default": next(iter(azure_subs), ""),
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
path = self._output_dir / "variables.tf.json"
|
|
557
|
+
with open(path, "w") as f:
|
|
558
|
+
json.dump({"variable": variables}, f, indent=2)
|
|
559
|
+
return path
|
|
560
|
+
|
|
561
|
+
def _generate_main(
|
|
562
|
+
self,
|
|
563
|
+
assets: list[CloudAsset],
|
|
564
|
+
containment_map: dict[str, str],
|
|
565
|
+
) -> Path:
|
|
566
|
+
"""Generate main.tf.json with all resource definitions."""
|
|
567
|
+
resources: dict[str, dict[str, dict[str, Any]]] = {}
|
|
568
|
+
|
|
569
|
+
for asset in assets:
|
|
570
|
+
tf_type = _TF_RESOURCE_MAP.get(asset.asset_type)
|
|
571
|
+
if not tf_type:
|
|
572
|
+
logger.debug("No Terraform mapping for asset type: %s", asset.asset_type.value)
|
|
573
|
+
continue
|
|
574
|
+
|
|
575
|
+
# Get transformer
|
|
576
|
+
transformer = _TRANSFORMERS.get(asset.asset_type, _transform_generic)
|
|
577
|
+
attrs = transformer(asset)
|
|
578
|
+
|
|
579
|
+
# Sanitise resource name for Terraform
|
|
580
|
+
tf_name = _sanitise_tf_name(asset.name)
|
|
581
|
+
|
|
582
|
+
# Ensure unique names within same resource type
|
|
583
|
+
if tf_type not in resources:
|
|
584
|
+
resources[tf_type] = {}
|
|
585
|
+
|
|
586
|
+
counter = 0
|
|
587
|
+
original_name = tf_name
|
|
588
|
+
while tf_name in resources[tf_type]:
|
|
589
|
+
counter += 1
|
|
590
|
+
tf_name = f"{original_name}_{counter}"
|
|
591
|
+
|
|
592
|
+
# Add comment-like metadata as lifecycle ignore
|
|
593
|
+
attrs["lifecycle"] = {"ignore_changes": ["tags"]}
|
|
594
|
+
|
|
595
|
+
resources[tf_type][tf_name] = attrs
|
|
596
|
+
|
|
597
|
+
# Structure as Terraform JSON
|
|
598
|
+
tf_json: dict[str, Any] = {"resource": resources}
|
|
599
|
+
|
|
600
|
+
path = self._output_dir / "main.tf.json"
|
|
601
|
+
with open(path, "w") as f:
|
|
602
|
+
json.dump(tf_json, f, indent=2, default=str)
|
|
603
|
+
return path
|
|
604
|
+
|
|
605
|
+
def _generate_import_commands(self, assets: list[CloudAsset]) -> Path:
|
|
606
|
+
"""Generate import_commands.sh with terraform import commands."""
|
|
607
|
+
lines = [
|
|
608
|
+
"#!/usr/bin/env bash",
|
|
609
|
+
"# CloudG — Terraform Import Commands",
|
|
610
|
+
"# Generated from collected cloud assets",
|
|
611
|
+
"# Run: chmod +x import_commands.sh && ./import_commands.sh",
|
|
612
|
+
"",
|
|
613
|
+
"set -euo pipefail",
|
|
614
|
+
"",
|
|
615
|
+
]
|
|
616
|
+
|
|
617
|
+
for asset in assets:
|
|
618
|
+
tf_type = _TF_RESOURCE_MAP.get(asset.asset_type)
|
|
619
|
+
if not tf_type:
|
|
620
|
+
continue
|
|
621
|
+
|
|
622
|
+
tf_name = _sanitise_tf_name(asset.name)
|
|
623
|
+
import_id = _get_import_id(asset)
|
|
624
|
+
|
|
625
|
+
lines.append(f'echo "Importing {tf_type}.{tf_name}..."')
|
|
626
|
+
lines.append(f"terraform import {tf_type}.{tf_name} {import_id}")
|
|
627
|
+
lines.append("")
|
|
628
|
+
|
|
629
|
+
lines.append('echo "✓ All imports complete"')
|
|
630
|
+
|
|
631
|
+
path = self._output_dir / "import_commands.sh"
|
|
632
|
+
with open(path, "w") as f:
|
|
633
|
+
f.write("\n".join(lines))
|
|
634
|
+
|
|
635
|
+
# Make executable
|
|
636
|
+
path.chmod(0o755)
|
|
637
|
+
|
|
638
|
+
return path
|
|
639
|
+
|
|
640
|
+
# ------------------------------------------------------------------
|
|
641
|
+
# Utility: summary of what would be generated
|
|
642
|
+
# ------------------------------------------------------------------
|
|
643
|
+
|
|
644
|
+
def preview(self, assets: list[CloudAsset]) -> dict[str, Any]:
|
|
645
|
+
"""Preview what Terraform resources would be generated without writing files.
|
|
646
|
+
|
|
647
|
+
Returns:
|
|
648
|
+
Summary dict with resource counts by type.
|
|
649
|
+
"""
|
|
650
|
+
type_counts: dict[str, int] = {}
|
|
651
|
+
unmapped: dict[str, int] = {}
|
|
652
|
+
|
|
653
|
+
for asset in assets:
|
|
654
|
+
tf_type = _TF_RESOURCE_MAP.get(asset.asset_type)
|
|
655
|
+
if tf_type:
|
|
656
|
+
type_counts[tf_type] = type_counts.get(tf_type, 0) + 1
|
|
657
|
+
else:
|
|
658
|
+
key = asset.asset_type.value
|
|
659
|
+
unmapped[key] = unmapped.get(key, 0) + 1
|
|
660
|
+
|
|
661
|
+
return {
|
|
662
|
+
"total_mapped": sum(type_counts.values()),
|
|
663
|
+
"total_unmapped": sum(unmapped.values()),
|
|
664
|
+
"resource_types": type_counts,
|
|
665
|
+
"unmapped_asset_types": unmapped,
|
|
666
|
+
}
|