#!/usr/bin/env python3 """Render the private Bedrock PostgreSQL config at deploy time.""" import argparse import ipaddress import json import os from pathlib import Path import re import tempfile from urllib.parse import quote def required(variable): value = os.environ.get(variable) if not value: raise SystemExit(f"Missing {variable}") return value def database_url(runner_loopback): host = required("BEDROCK_PG_HOST").removeprefix("[").removesuffix("]") if runner_loopback and host not in ("127.0.0.1", "::1"): raise SystemExit("--runner-loopback requires a loopback IP literal") if ":" in host: try: host = f"[{ipaddress.IPv6Address(host)}]" except ValueError: raise SystemExit("Invalid BEDROCK_PG_HOST") from None elif not re.fullmatch(r"[A-Za-z0-9.-]+", host): raise SystemExit("Invalid BEDROCK_PG_HOST") try: port = int(required("BEDROCK_PG_PORT")) if not 1 <= port <= 65535: raise ValueError except ValueError: raise SystemExit("Invalid BEDROCK_PG_PORT") from None user = quote(required("BEDROCK_PG_USER"), safe="") password = quote(required("BEDROCK_PG_PASSWORD"), safe="") database = quote(required("BEDROCK_PG_DATABASE"), safe="") return f"postgres://{user}:{password}@{host}:{port}/{database}" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("output", type=Path) parser.add_argument("--deployment", default="default") parser.add_argument("--config-version", default="local") parser.add_argument( "--runner-loopback", action="store_true", help="connect without TLS to a loopback IP from the runner's host network", ) options = parser.parse_args() if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment): parser.error("invalid deployment name") if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.config_version): parser.error("invalid config version") # JSON quoting is valid for scalars in YAML and handles special characters. config = ( f"deployment: {json.dumps(options.deployment)}\n" f"config_version: {json.dumps(options.config_version)}\n" "bindings:\n" " documents: postgres\n" "resources:\n" " postgres:\n" " kind: sql\n" " driver: postgres\n" f" primary: {json.dumps(database_url(options.runner_loopback))}\n" ) if options.runner_loopback: config += " tls: disabled\n" # Write with owner-only permissions, then replace the destination atomically. file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False) try: with file: file.write(config) os.replace(file.name, options.output) finally: Path(file.name).unlink(missing_ok=True) if __name__ == "__main__": main()