Spaces:
Runtime error

ai-tester-platform / scripts /push_env_to_render.py
BattleFiven's picture
deploy: round 6 save_intermediate light (sha 05316bb)
ed86a97
Raw History Blame Contribute Delete
10 kB
"""Push a batch of env vars from a .env file to a Render service.
Wraps Render's REST API ``PUT /services/{id}/env-vars/{key}`` so the operator
can:
1. Edit ``.env.production`` (gitignored) once
2. Run this script
3. Render redeploys with the new env
Connection details:
--service-id srv-… (also reads RENDER_SERVICE_ID env)
--api-key rnda_… (also reads RENDER_API_KEY env)
Source file selection:
--env-file path (default: .env.production.local then .env.production)
Safety:
- Skips lines that look like comments / blanks.
- Refuses to push values containing literal "your_…_here" placeholders
(unless --force is given) β€” those are template stubs.
- Dry-run mode prints what *would* be sent without hitting the API.
- Only updates keys listed in --include (if given) or excluded by --exclude.
- Logs masked previews of secret values (last 4 chars).
Usage::
# Dry-run from .env.production.local
python scripts/push_env_to_render.py --dry-run
# Real run
RENDER_API_KEY=rnda_xxx RENDER_SERVICE_ID=srv-xxx \
python scripts/push_env_to_render.py
# Selective push
python scripts/push_env_to_render.py \
--include APP_SECRETS_MASTER_KEY,DATABASE_URL,SUPABASE_URL
After a successful push Render auto-deploys (unless auto-deploy is disabled).
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Set
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
DEFAULT_CANDIDATES = (".env.production.local", ".env.production")
PLACEHOLDER_MARKERS = ("your_", "_here", "xxx_replace_me", "<your-", "[pending", "[db_password")
REPO_ROOT = Path(__file__).resolve().parent.parent
def _autoload_env() -> None:
"""Auto-load .env.production.local so that --service-id / --api-key
fall back to env vars when not provided on the command line."""
for candidate in DEFAULT_CANDIDATES:
path = REPO_ROOT / candidate
if not path.exists():
continue
try:
from dotenv import load_dotenv # type: ignore[import-not-found]
load_dotenv(path, override=False)
except ImportError:
for line in path.read_text(encoding="utf-8").splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#") or "=" not in stripped:
continue
key, _, value = stripped.partition("=")
os.environ.setdefault(key.strip(), value.strip().strip("'\""))
return
_autoload_env()
# Control-plane variables β€” only consumed by deploy scripts locally.
# Never push these to the Render service: they'd be useless at runtime
# and the API key in particular would be a privilege escalation hazard.
DEFAULT_EXCLUDED_KEYS: Set[str] = {
"RENDER_API_KEY",
"RENDER_SERVICE_ID",
"RENDER_PUBLIC_URL",
"SUPABASE_DB_URL", # duplicate of DATABASE_URL; only used by apply_supabase_schema.py
}
def _mask(value: str) -> str:
if not value:
return "(empty)"
if len(value) <= 8:
return "****"
return f"{value[:2]}…{value[-4:]}"
def _looks_like_placeholder(value: str) -> bool:
low = value.strip().lower()
return any(marker in low for marker in PLACEHOLDER_MARKERS)
def parse_env_file(path: Path) -> Dict[str, str]:
result: Dict[str, str] = {}
if not path.exists():
return result
for line_no, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
continue
if "=" not in stripped:
continue
key, _, value = stripped.partition("=")
# Strip surrounding quotes if present.
v = value.strip()
if (v.startswith('"') and v.endswith('"')) or (v.startswith("'") and v.endswith("'")):
v = v[1:-1]
result[key.strip()] = v
return result
def _select_env_file(explicit: Optional[Path]) -> Path:
if explicit:
if not explicit.exists():
raise SystemExit(f"--env-file not found: {explicit}")
return explicit
for candidate in DEFAULT_CANDIDATES:
p = Path(candidate)
if p.exists():
return p
raise SystemExit(
f"no env file found β€” looked for {' or '.join(DEFAULT_CANDIDATES)}; "
"pass --env-file"
)
def render_put_env_var(
base_url: str,
service_id: str,
api_key: str,
key: str,
value: str,
timeout: float = 20.0,
) -> Dict[str, object]:
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-batch",
},
data=payload,
)
with urlopen(req, timeout=timeout) as response:
body = response.read().decode("utf-8", errors="ignore").strip()
return {
"ok": True,
"status": int(getattr(response, "status", 200) or 200),
"body": body[:300] if body else "",
}
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--service-id", default=os.getenv("RENDER_SERVICE_ID", ""))
parser.add_argument("--api-key", default=os.getenv("RENDER_API_KEY", ""))
parser.add_argument("--env-file", type=Path, default=None)
parser.add_argument("--base-url", default="https://api.render.com/v1")
parser.add_argument("--dry-run", action="store_true", help="Don't hit the API")
parser.add_argument(
"--include",
default="",
help="Comma-separated allowlist; if set, only these keys are pushed",
)
parser.add_argument(
"--exclude",
default="",
help="Comma-separated denylist; these keys are never pushed",
)
parser.add_argument(
"--force",
action="store_true",
help="Push values that look like placeholder text (your_..._here)",
)
parser.add_argument(
"--throttle-seconds",
type=float,
default=0.4,
help="Sleep between PUT calls to avoid Render API rate limits",
)
args = parser.parse_args()
src = _select_env_file(args.env_file)
pairs = parse_env_file(src)
if not pairs:
print(f"no usable key=value lines in {src}", file=sys.stderr)
return 2
include: Set[str] = {s.strip() for s in args.include.split(",") if s.strip()}
user_exclude: Set[str] = {s.strip() for s in args.exclude.split(",") if s.strip()}
# Default exclusions are always applied unless --include explicitly
# selects the key (escape hatch for advanced users who really want to
# push a control-plane var).
effective_exclude = user_exclude | (DEFAULT_EXCLUDED_KEYS - include)
selected: List[tuple[str, str]] = []
skipped_placeholder: List[str] = []
skipped_excluded: List[str] = []
for key, value in pairs.items():
if include and key not in include:
continue
if key in effective_exclude:
skipped_excluded.append(key)
continue
if _looks_like_placeholder(value) and not args.force:
skipped_placeholder.append(key)
continue
selected.append((key, value))
print(f"\npush_env_to_render: source={src}, target_count={len(selected)}\n")
for key, value in selected:
print(f" {key:30s} = {_mask(value)}")
if skipped_placeholder:
print("\nskipped (look like template placeholders, --force to push anyway):")
for k in skipped_placeholder:
print(f" - {k}")
if skipped_excluded:
print("\nskipped (control-plane only, never pushed to Render):")
for k in skipped_excluded:
print(f" - {k}")
print()
if args.dry_run:
print("dry-run: not calling Render API")
return 0
if not args.service_id or not args.api_key:
print(
"missing creds β€” provide --service-id and --api-key, or set "
"RENDER_SERVICE_ID + RENDER_API_KEY in env",
file=sys.stderr,
)
return 2
failures: List[tuple[str, str]] = []
for key, value in selected:
try:
res = render_put_env_var(
base_url=args.base_url,
service_id=args.service_id,
api_key=args.api_key,
key=key,
value=value,
)
print(f" βœ“ {key} http {res.get('status')}")
except HTTPError as exc:
body = ""
try:
body = exc.read().decode("utf-8", errors="ignore")[:300]
except Exception:
body = str(exc)
failures.append((key, f"HTTP {exc.code}: {body}"))
print(f" βœ— {key} HTTP {exc.code}: {body}", file=sys.stderr)
except URLError as exc:
failures.append((key, str(exc)))
print(f" βœ— {key} network: {exc}", file=sys.stderr)
except Exception as exc:
failures.append((key, str(exc)))
print(f" βœ— {key} {exc}", file=sys.stderr)
time.sleep(max(0.0, args.throttle_seconds))
print()
if failures:
print(f"push_env_to_render: FAILED on {len(failures)} key(s):")
for key, msg in failures:
print(f" - {key}: {msg}")
return 1
print(f"push_env_to_render: pushed {len(selected)} keys βœ“")
print("Render will auto-deploy unless auto-deploy is disabled on the service.")
return 0
if __name__ == "__main__":
sys.exit(main())