Files
mtusi2026lab6/scripts/init_local_broker.py

39 lines
1.1 KiB
Python

#!/usr/bin/env python3
"""Create local RabbitMQ credentials without writing them to tracked files."""
from pathlib import Path
from secrets import token_hex
from urllib.parse import quote
root = Path(__file__).resolve().parents[1]
secret_dir = root / "secrets"
secret_dir.mkdir(mode=0o700, exist_ok=True)
secret_dir.chmod(0o700)
config = secret_dir / "rabbitmq.conf"
url_file = secret_dir / "broker_url"
username = "lab5_app"
if config.exists():
values = dict(
line.split(" = ", 1)
for line in config.read_text(encoding="utf-8").splitlines()
if " = " in line
)
if values.get("default_user") != username or not values.get("default_pass"):
raise SystemExit("Existing RabbitMQ config cannot be reused")
password = values["default_pass"]
else:
password = token_hex(24)
config.write_text(
f"default_user = {username}\ndefault_pass = {password}\n",
encoding="utf-8",
)
config.chmod(0o600)
url_file.write_text(
f"amqp://{username}:{quote(password, safe='')}@broker:5672/%2F\n",
encoding="utf-8",
)
url_file.chmod(0o600)
print("Local broker credentials are ready in ignored secrets/")