Files
mtusi2026lab5/scripts/bootstrap.py
T

49 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""Create local synthetic credentials once, without printing their values."""
import os
import secrets
from pathlib import Path
root = Path(__file__).resolve().parents[1]
directory = root / "secrets"
directory.mkdir(mode=0o700, exist_ok=True)
password_file = directory / "postgres_password"
if not password_file.exists():
password_file.write_text(secrets.token_urlsafe(32) + "\n")
password = password_file.read_text().strip()
for name, value in {
"database_url": f"postgresql://messenger:{password}@postgres:5432/messenger",
"cache_url": "redis://valkey:6379/0",
"broker_url": "redis://broker:6379/0",
}.items():
path = directory / name
if not path.exists():
path.write_text(value + "\n")
# Compose bind-mount secrets must be readable by the non-root container process.
# The parent directory remains 0700 on the host.
for role in ("root", "api", "worker", "reconciler", "test"):
names = (
("s3_root_user", "s3_root_password")
if role == "root"
else ("s3_" + role + "_access_key_id", "s3_" + role + "_secret_access_key")
)
for index, name in enumerate(names):
path = directory / name
if not path.exists():
path.write_text(
(secrets.token_hex(10) if index == 0 else secrets.token_urlsafe(32)) + "\n"
)
for name in (
"postgres_password",
"database_url",
"cache_url",
"broker_url",
*[p.name for p in directory.glob("s3_*")],
):
os.chmod(directory / name, 0o644)
env = root / ".env"
if not env.exists():
env.write_text((root / ".env.example").read_text())
print("Local secret files and environment are ready; existing values preserved.")