storage/init/postgres-init.sh
Sergei Poljanski d009d2c3d2
postgres-init: grant the bingo monitor tables to bingo
asxpio's migration 017 adds bingo_monitor_targets, _samples and
_buckets for datacenterbingo's status page. The migration grants them
itself; list them here too so a fresh install gets the same grants.

Assisted-by: Claude:opus-5-5
2026-10-18 10:31:01 +04:00

62 lines
1.9 KiB
Bash

#!/bin/sh
# Idempotent bootstrap: create per-app roles and databases.
# Re-running is safe — checks before creating, updates passwords if changed.
set -eu
ensure_role() {
role="$1"
password="$2"
exists=$(psql -tAc "SELECT 1 FROM pg_roles WHERE rolname='${role}'")
if [ "${exists}" = "1" ]; then
psql -c "ALTER ROLE \"${role}\" WITH LOGIN PASSWORD '${password}';"
else
psql -c "CREATE ROLE \"${role}\" WITH LOGIN PASSWORD '${password}';"
fi
}
ensure_db() {
db="$1"
owner="$2"
exists=$(psql -tAc "SELECT 1 FROM pg_database WHERE datname='${db}'")
if [ "${exists}" != "1" ]; then
psql -c "CREATE DATABASE \"${db}\" OWNER \"${owner}\";"
fi
}
ensure_extension() {
db="$1"
ext="$2"
psql -d "${db}" -c "CREATE EXTENSION IF NOT EXISTS \"${ext}\";"
}
ensure_role "asxpio" "${ASXPIO_DB_PASSWORD}"
ensure_db "asxpio" "asxpio"
ensure_extension "asxpio" "citext"
# datacenterbingo: read-only on the bingo tables in the asxpio DB (asxpio's
# admin writes them and owns the schema). Tables that don't exist yet (fresh
# install, asxpio not migrated) are granted on the next storage deploy.
if [ -n "${BINGO_DB_PASSWORD:-}" ]; then
ensure_role "bingo" "${BINGO_DB_PASSWORD}"
psql -c "ALTER ROLE bingo SET default_transaction_read_only = on;"
psql -d asxpio -v ON_ERROR_STOP=1 <<'SQL' # heredoc body stays at column 0
GRANT CONNECT ON DATABASE asxpio TO bingo;
GRANT USAGE ON SCHEMA public TO bingo;
DO $$
DECLARE t text;
BEGIN
FOREACH t IN ARRAY ARRAY['bingo_datacenters', 'bingo_incidents', 'bingo_monitor_targets',
'bingo_monitor_samples', 'bingo_monitor_buckets'] LOOP
IF to_regclass('public.' || t) IS NOT NULL THEN
EXECUTE format('GRANT SELECT ON public.%I TO bingo', t);
ELSE
RAISE NOTICE 'bingo: % missing, not granted yet', t;
END IF;
END LOOP;
END $$;
SQL
else
echo "postgres-init: BINGO_DB_PASSWORD unset, skipping bingo role"
fi
echo "postgres-init: done"