Files
mtusi2026lab7/scripts/bootstrap-rabbitmq-credentials.py
T

124 lines
3.2 KiB
Python

#!/usr/bin/env python3
"""Create separate RabbitMQ service accounts without printing passwords."""
import os
import secrets
import subprocess
from pathlib import Path
ENV_FILE = Path(".env")
ACCOUNTS = {
"messenger_publisher": {
"env": "RABBITMQ_PUBLISHER_PASSWORD",
"configure": "^image_jobs$",
"write": r"^amq\.default$",
"read": "^$",
},
"messenger_consumer": {
"env": "RABBITMQ_CONSUMER_PASSWORD",
"configure": "^image_jobs$",
"write": "^$",
"read": "^image_jobs$",
},
}
def rabbitmqctl(*arguments, password=None):
command = [
"docker", "compose", "exec", "-T",
"rabbitmq", "rabbitmqctl",
*arguments,
]
result = subprocess.run(
command,
input=None if password is None else password + "\n",
text=True,
capture_output=True,
)
if result.returncode != 0:
raise RuntimeError(
"RabbitMQ command failed: " + arguments[0]
)
return result.stdout
def main():
if not ENV_FILE.is_file():
raise SystemExit("ERROR: .env not found")
contents = ENV_FILE.read_text(encoding="utf-8")
for account in ACCOUNTS.values():
key = account["env"]
if any(
line.strip().startswith(key + "=")
for line in contents.splitlines()
):
raise SystemExit(
f"ERROR: {key} already exists in .env"
)
try:
existing_users = rabbitmqctl("list_users")
except RuntimeError as exc:
raise SystemExit(str(exc))
for username in ACCOUNTS:
if any(
line.split("\t")[0].strip() == username
for line in existing_users.splitlines()
):
raise SystemExit(
f"ERROR: {username} already exists in RabbitMQ"
)
generated = {}
try:
for username, settings in ACCOUNTS.items():
password = secrets.token_hex(32)
rabbitmqctl(
"add_user", username,
password=password,
)
rabbitmqctl(
"set_permissions",
"-p", "/",
username,
settings["configure"],
settings["write"],
settings["read"],
)
generated[settings["env"]] = password
print(f"PASS: {username} created with scoped ACL")
except RuntimeError as exc:
print("ERROR:", exc)
print(
"RabbitMQ may contain partially created accounts. "
"Do not rerun automatically."
)
raise SystemExit(1)
with ENV_FILE.open("a", encoding="utf-8") as file:
file.write("\n# Lab7 RabbitMQ service credentials\n")
for key, password in generated.items():
file.write(f"{key}={password}\n")
os.chmod(ENV_FILE, 0o600)
print("PASS: RabbitMQ passwords stored in ignored .env")
print("PASS: No passwords printed")
print("Existing application credentials were not changed")
if __name__ == "__main__":
main()