import json import os import sys from typing import Any, Dict, List import requests # Configuration API_KEY = os.environ.get("API_KEY") URL_DEVICES = "https://10.1.0.1/proxy/network/v2/api/site/default/static-dns/devices" URL_POLICIES = "https://10.1.0.1/proxy/network/integration/v1/sites/88f7af54-98f8-306a-a1c7-c9349722b1f6/dns/policies" OUTPUT_FILE = "active/aws_route53/secrets/unifi_reeselink_records.json" ALLOWED_DOMAIN = "reeselink.com" FIXED_TTL = 60 # Headers headers = {"Accept": "application/json", "X-API-Key": API_KEY} def fetch_json(url: str) -> Any: """Helper to perform the GET request and return parsed JSON.""" response = requests.get( url, headers=headers, verify=False, # -k: Don't verify SSL certificate allow_redirects=True, # -L: Follow redirects ) if response.status_code != 200: print(f"Error: Received status code {response.status_code} from {url}") print(f"Response: {response.text}") sys.exit(1) return response.json() def main(): all_changes: List[Dict[str, Any]] = [] # 1. Process Devices API devices_data = fetch_json(URL_DEVICES) devices_count = 0 # devices_data is expected to be a list: [{hostname: ..., ip_address: ...}, ...] for device in devices_data: hostname = device.get("hostname", "") ip = device.get("ip_address", "") if hostname.endswith(ALLOWED_DOMAIN): all_changes.append( { "Action": "UPSERT", "ResourceRecordSet": { "Name": hostname, "Type": "A", "TTL": FIXED_TTL, "ResourceRecords": [{"Value": ip}], }, } ) devices_count += 1 # 2. Process Policies API policies_response = fetch_json(URL_POLICIES) policies_count = 0 # policies_response is expected to be a dict: {"data": [{domain: ..., ipv4Address: ...}, ...]} policies_list = policies_response.get("data", []) for policy in policies_list: domain = policy.get("domain", "") ip = policy.get("ipv4Address", "") if domain.endswith(ALLOWED_DOMAIN): all_changes.append( { "Action": "UPSERT", "ResourceRecordSet": { "Name": domain, "Type": "A", "TTL": FIXED_TTL, "ResourceRecords": [{"Value": ip}], }, } ) policies_count += 1 # Construct Final AWS Payload final_payload = { "Comment": "Combined records from Unifi devices and policies", "Changes": all_changes, } # Write to file try: # Ensure directory exists os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True) with open(OUTPUT_FILE, "w") as f: json.dump(final_payload, f, indent=4) except Exception as e: print(f"Error writing to file: {e}") sys.exit(1) # Print Summary print(f"Successfully processed records:") print(f" - devices: {devices_count}") print(f" - policies: {policies_count}") print(f"Total records in file: {len(all_changes)}") print(f"Saved to {OUTPUT_FILE}") if __name__ == "__main__": # Suppress InsecureRequestWarning for verify=False requests.packages.urllib3.disable_warnings() # type: ignore main()