Files
mtusi2026lab2/scripts/bootstrap.py

31 lines
1.3 KiB
Python

#!/usr/bin/env python3
"""Generate local credentials once, without printing or committing their values."""
import os
from pathlib import Path
import secrets
ROOT = Path(__file__).resolve().parents[1]
folder = ROOT / 'secrets'
folder.mkdir(mode=0o700, exist_ok=True)
def write_once(name, value):
path = folder / name
if not path.exists():
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor,'w') as file:
file.write(value + '\n')
# Parent directory is 0700 on the host; mounted files must also be readable
# by nonroot service UIDs inside their explicitly selected containers.
path.chmod(0o644)
return path.read_text().strip()
password = write_once('db_password', secrets.token_hex(24))
cache_password = write_once('cache_password', secrets.token_hex(24))
write_once('database_url', f'postgresql://messenger:{password}@postgres:5432/messenger')
write_once('cache_url', f'redis://:{cache_password}@valkey:6379/0')
write_once('valkey.conf', f'bind 0.0.0.0\nprotected-mode yes\nport 6379\nrequirepass {cache_password}\nmaxmemory 64mb\nmaxmemory-policy allkeys-lru\nsave ""\nappendonly no\n')
env = ROOT / '.env'
if not env.exists():
env.write_text((ROOT / '.env.example').read_text())
print('PASS: local secret files ready; existing credentials preserved; values not printed')