#!/usr/bin/env python3 """Sync a Render service environment variable through Render API. Examples: python scripts/sync_render_env_var.py \ --service-id srv-xxxxxxxx \ --api-key rnda_xxxxx \ --key DESKTOP_APP_LATEST_VERSION \ --value 1.0.2 python scripts/sync_render_env_var.py \ --service-id srv-xxxxxxxx \ --api-key rnda_xxxxx \ --key DESKTOP_APP_LATEST_VERSION \ --value-from-build-info desktop/app/build_info.py """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path from urllib.error import HTTPError, URLError from urllib.parse import quote from urllib.request import Request, urlopen def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description="Update a Render env var") parser.add_argument("--service-id", required=True, help="Render service ID (srv-...)") parser.add_argument("--api-key", required=True, help="Render API key") parser.add_argument("--key", required=True, help="Environment variable name") parser.add_argument("--value", default="", help="New value for env var") parser.add_argument( "--value-from-build-info", default="", help="Path to build_info.py containing DESKTOP_APP_VERSION", ) parser.add_argument("--base-url", default="https://api.render.com/v1", help="Render API base URL") return parser.parse_args() def read_version_from_build_info(path: Path) -> str: content = path.read_text(encoding="utf-8", errors="ignore") match = re.search(r'DESKTOP_APP_VERSION\s*=\s*"([^"]+)"', content) if not match: raise ValueError("DESKTOP_APP_VERSION not found in build_info.py") return str(match.group(1)).strip() def update_env_var(base_url: str, service_id: str, api_key: str, key: str, value: str) -> dict: endpoint = f"{base_url.rstrip('/')}/services/{quote(service_id)}/env-vars/{quote(key)}" payload = json.dumps({"value": value}).encode("utf-8") req = Request( endpoint, method="PUT", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "ai-tester-platform/render-env-sync", }, data=payload, ) with urlopen(req, timeout=20) as response: body = response.read().decode("utf-8", errors="ignore").strip() if not body: return {"ok": True, "status": int(getattr(response, "status", 200) or 200)} try: parsed = json.loads(body) except Exception: parsed = {"raw": body} parsed["ok"] = True return parsed def main() -> int: args = parse_args() value = str(args.value or "").strip() if not value and args.value_from_build_info: build_info_path = Path(args.value_from_build_info).expanduser().resolve() if not build_info_path.exists(): raise SystemExit(f"Build info file not found: {build_info_path}") value = read_version_from_build_info(build_info_path) if not value: raise SystemExit("Missing value. Provide --value or --value-from-build-info.") try: result = update_env_var( base_url=str(args.base_url), service_id=str(args.service_id), api_key=str(args.api_key), key=str(args.key), value=value, ) print(json.dumps({"ok": True, "key": args.key, "value": value, "result": result}, ensure_ascii=True)) return 0 except HTTPError as exc: error_body = "" try: error_body = exc.read().decode("utf-8", errors="ignore") except Exception: error_body = str(exc) print( json.dumps( { "ok": False, "error": f"HTTP {exc.code}", "detail": error_body[:800], "key": args.key, "value": value, }, ensure_ascii=True, ), file=sys.stderr, ) return 1 except URLError as exc: print(json.dumps({"ok": False, "error": f"Network error: {exc}"}, ensure_ascii=True), file=sys.stderr) return 1 except Exception as exc: print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=True), file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())