server-scripts/create-postgres-user-and-da...

33 lines
566 B
Bash
Executable File

#!/usr/bin/env bash
set -eu
if [ $# -lt 1 ]
then
echo "Usage: $0 <username> [<database>]"
exit 1
fi
if ! [ $EUID -eq 0 ]
then
echo "Must be root!" >&2
exit 1
fi
USER="$1"
DBPASSWORD="$(tr -dc A-Za-z0-9 < /dev/urandom | head -c 64)"
DATABASE="${2:-$USER}"
lxc-attach -n postgres -- su postgres -c psql <<EOF
create user "$USER";
alter user "$USER" with password '$DBPASSWORD';
create database "$DATABASE" with owner "$USER";
grant all privileges on database "$DATABASE" to "$USER";
EOF
echo
echo "Password for user $USER is:"
echo
echo $DBPASSWORD
echo