Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
badra001 committed Mar 27, 2026
1 parent f64c2f3 commit 8b8300c
Showing 1 changed file with 30 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@
import os
import glob
import csv
import argparse
from datetime import datetime
from collections import defaultdict

# --- VERSIONING ---
__version__ = "1.7.4"
__version__ = "1.7.8"

def get_tag(tags, key, default=""):
"""Case-insensitive tag lookup."""
if not tags: return default
# Handle list of dicts if AWS API returned raw format
if isinstance(tags, list):
tags = {t['Key']: t['Value'] for t in tags if 'Key' in t}
if not tags or not isinstance(tags, dict): return default
for k, v in tags.items():
if k.lower() == key.lower():
return v.strip() if v else default
Expand All @@ -36,11 +34,13 @@ def generate_master_resource_csv(all_resources, ts):
writer = csv.DictWriter(f, fieldnames=fields)
writer.writeheader()
for res in all_resources:
# Use 'resource' key as fallback for 'arn' based on your JSON snippet
arn = res.get('resource') or res.get('arn', 'N/A')
row = {
"account_id": res.get('account_id', 'N/A'),
"region": res.get('region', 'N/A'),
"type": res.get('type', 'N/A'),
"arn": res.get('arn', 'N/A')
"arn": arn
}
for tag in target_tags:
row[tag] = get_tag(res.get('tags', {}), tag)
Expand All @@ -50,12 +50,14 @@ def generate_master_resource_csv(all_resources, ts):
return f"Error: {str(e)}"

def main():
parser = argparse.ArgumentParser(description=f"Scheduling Assessor v{__version__}")
parser.add_argument("--debug", action="store_true", help="Enable verbose debugging")
args = parser.parse_args()

ts = datetime.now().strftime("%Y%m%dT%H%M%S")
all_res = []

# MATCHING THE SPECIFIC FILENAME PATTERN
audit_files = glob.glob("audit_results.check_scheduling.*.json")

if not audit_files:
print(f"❌ Error: No files matching 'audit_results.check_scheduling.*.json' found.")
return
Expand All @@ -65,34 +67,35 @@ def main():
for file_path in audit_files:
with open(file_path, 'r') as f:
try:
# FIX: audit_results is a LIST of account objects
account_list = json.load(f)
account_entries = json.load(f)
file_count = 0

if not isinstance(account_list, list):
print(f" Warning: {file_path} is not a list. Skipping.")
continue

for account_entry in account_list:
# Each entry has an 'account_id' key and its associated data
for acc_id, acc_content in account_entry.items():
if not isinstance(acc_content, dict) or "data" not in acc_content:
# Iterate through the list of account objects
for entry in account_entries:
acc_id = entry.get("account_id", "Unknown")
data_block = entry.get("data", {})

if not data_block:
continue

for res_id, res_info in data_block.items():
# Skip the summary metadata
if res_id == "account_summary":
continue

# Extract the resources from the 'data' block
for res_key, res_info in acc_content["data"].items():
# Skip the metadata summary entry
if res_key == "account_summary":
continue

# Inject account context into the resource for the CSV
if isinstance(res_info, dict):
# Inject account context for the CSV output
res_info['account_id'] = acc_id
all_res.append(res_info)

file_count += 1

if args.debug:
print(f" [DEBUG] Found {file_count} resources in {file_path}")
except Exception as e:
print(f" Skipping {file_path} due to error: {e}")

if not all_res:
print("❌ Error: No resource data could be extracted. Please verify the JSON contents."); return
print("❌ Error: No resource data could be extracted. Check JSON structure."); return

# --- FINOPS HEALTH REPORT ---
missing_num = sum(1 for r in all_res if not get_tag(r.get('tags', {}), 'finops_project_number'))
Expand Down Expand Up @@ -121,7 +124,6 @@ def main():
pct = (counts['scheduled'] / counts['total']) * 100
print(f"{env:<25} | {counts['total']:<8} | {counts['scheduled']:<12} | {pct:.1f}%")

# --- CSV GENERATION ---
print("\nGENERATING REPORTS...")
master_file = generate_master_resource_csv(all_res, ts)
print(f" [DONE] Created Master Inventory: {master_file}")
Expand Down

0 comments on commit 8b8300c

Please sign in to comment.