#!/usr/bin/env python3 """Create local secret files for the compose stand. python scripts/init_secrets.py Passwords are random and synthetic; they are created only if missing and never printed. The URL/config files are always rebuilt from the password files, so the pair stays consistent. secrets/ is listed in .gitignore and .dockerignore. PostgreSQL applies its password only when the data volume is created. If secrets/ is deleted while the pgdata volume is kept, restore the old files or recreate the volume (docker compose down -v deletes ALL lab data). """ from pathlib import Path import secrets ROOT = Path(__file__).resolve().parents[1] DIR = ROOT / 'secrets' def write(name, content): path = DIR / name path.write_text(content, encoding='utf-8', newline='\n') # Readable for the non-root users inside containers (files are bind-mounted as is). path.chmod(0o644) def password(name): path = DIR / name if path.is_file() and path.read_text(encoding='utf-8').strip(): print('keep secrets/' + name) return path.read_text(encoding='utf-8').strip() value = secrets.token_hex(24) # hex: safe inside URLs without escaping write(name, value + '\n') print('created secrets/' + name) return value def main(): DIR.mkdir(exist_ok=True) postgres = password('postgres_password') valkey = password('valkey_password') write('database_url', 'postgresql://messenger:%s@postgres:5432/messenger\n' % postgres) write('valkey_auth', 'requirepass %s\n' % valkey) write('cache_url', 'valkey://:%s@valkey:6379/0\n' % valkey) print('written secrets/database_url, secrets/valkey_auth, secrets/cache_url') if __name__ == '__main__': main()