Files
homelab/.gitea/scripts/process-terraform-output.py
AB from home.homenet 3e4f5500d2
All checks were successful
Terraform / Terraform (push) Successful in 31s
Added wiki generator
2025-09-16 16:15:39 +03:00

105 lines
3.0 KiB
Python

#!/usr/bin/env python3
"""
Process Terraform output to extract applications_for_wiki data
Handles various output formats and cleans up invalid JSON
"""
import json
import sys
import os
def clean_command_prefix(content):
"""Remove [command] prefix if present"""
if content.startswith('[command]'):
lines = content.split('\n', 1)
if len(lines) > 1:
return lines[1]
return content
def extract_valid_json(content):
"""Extract valid JSON from content that might have extra data"""
# Find first { and last matching }
start = content.find('{')
if start < 0:
return None
count = 0
end = start
for i in range(start, len(content)):
if content[i] == '{':
count += 1
elif content[i] == '}':
count -= 1
if count == 0:
end = i + 1
break
if end > start and count == 0:
return content[start:end]
return None
def extract_value(data):
"""Extract value from Terraform output format"""
if isinstance(data, dict) and 'value' in data:
return data['value']
return data
def main():
if len(sys.argv) != 3:
print("Usage: process-terraform-output.py <input-file> <output-file>")
sys.exit(1)
input_file = sys.argv[1]
output_file = sys.argv[2]
try:
# Read input file
with open(input_file, 'r') as f:
content = f.read()
# Clean command prefix if present
content = clean_command_prefix(content)
# Try to parse JSON directly
try:
data = json.loads(content)
print("✅ Valid JSON parsed successfully")
except json.JSONDecodeError as e:
print(f"⚠️ Initial JSON parse failed: {e}")
print("🔍 Attempting to extract valid JSON portion...")
# Try to extract valid JSON
valid_json = extract_valid_json(content)
if valid_json:
try:
data = json.loads(valid_json)
print("✅ Extracted valid JSON successfully")
except json.JSONDecodeError as e2:
print(f"❌ Failed to parse extracted JSON: {e2}")
sys.exit(1)
else:
print("❌ Could not extract valid JSON from content")
sys.exit(1)
# Extract value if it's wrapped in Terraform output format
result = extract_value(data)
# Write output
with open(output_file, 'w') as f:
json.dump(result, f, indent=2)
print(f"✅ Processed output written to {output_file}")
# Show preview
preview = json.dumps(result, indent=2)[:200]
print(f"📄 Preview: {preview}...")
except FileNotFoundError:
print(f"❌ Input file {input_file} not found")
sys.exit(1)
except Exception as e:
print(f"❌ Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()