Files
mtusi2026lab2/scripts/init-secrets.sh
T

43 lines
1.4 KiB
Bash
Executable File

#!/bin/sh
# Creates the local credentials of the compose stand in ./secrets, which git
# ignores. Existing secrets are kept: PostgreSQL applies its password only
# when the volume is first initialised, so a new password would lock the API
# out of an existing database. To start over: make destroy, then delete
# ./secrets and run this again.
set -eu
cd "$(dirname "$0")/.."
files="postgres_password database_url valkey_auth.conf session_store_url"
present=0
for f in $files; do
if [ -e "secrets/$f" ]; then
present=$((present + 1))
fi
done
if [ "$present" -eq 4 ]; then
echo "secrets already exist in ./secrets, kept"
exit 0
fi
if [ "$present" -ne 0 ]; then
echo "./secrets is incomplete: delete it (and run make destroy if the stand holds data), then run again" >&2
exit 1
fi
# 24 random bytes as hex: URL-safe without escaping.
random() {
od -An -tx1 -N24 /dev/urandom | tr -d ' \n'
}
pg=$(random)
kv=$(random)
# The directory is private; the files stay readable for the unprivileged
# users inside the containers, which see them through bind mounts.
umask 022
mkdir -p secrets
chmod 700 secrets
printf '%s\n' "$pg" > secrets/postgres_password
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable\n' "$pg" > secrets/database_url
printf 'requirepass %s\n' "$kv" > secrets/valkey_auth.conf
printf 'redis://:%s@valkey:6379/0\n' "$kv" > secrets/session_store_url
echo "created ./secrets"