Commit 05ed895e authored by Jo's avatar Jo
Browse files

feat(ensure-db): first draft

parent 2d429e6d
#!/bin/bash
set +x
set -e
#
# create a new user and DB on a remote Azure Postgres server
#
# Some weirdness due to "@" characters in Azure connection strings and SSL config and extensions security
#
PGUSER=${PGUSER:-postgres}
PGPORT=${PGPORT:-5432}
PGHOST=${PGHOST:--127.0.0.1}
# check mandatory environment variables
MANDATORY_VARS="PGPASSWORD NEW_DB_NAME NEW_USER NEW_PASSWORD"
for VAR in $MANDATORY_VARS; do
if [[ -z "${!VAR}" ]]; then
echo "${VAR} environment variable is empty"
exit 1
fi
done
# full urls with arobase replacement
PG_URL_ADMIN="postgresql://${PGUSER/@/%40}:${PGPASSWORD/@/%40}@${PGHOST}:${PGPORT}/postgres"
PG_URL_NEWDB="postgresql://${PGUSER/@/%40}:${PGPASSWORD/@/%40}@${PGHOST}:${PGPORT}/${NEW_DB_NAME}"
PGSSLMODE=require
# /o\ get base user name (without server) for SQL commands
NEW_USER_BASE=${NEW_USER%%@*} || $NEW_USER
if psql -abe "$PG_URL_ADMIN" -c "\c ${NEW_DB_NAME}"; then
echo "Database already exist, skip creation"
else
echo "Creating database ${NEW_DB_NAME} on ${PGHOST}"
psql -abe "$PG_URL_ADMIN" -c "CREATE DATABASE \"$NEW_DB_NAME\";"
echo "Creating database extensions ${NEW_DB_NAME}"
if [[ -n "${NEW_DB_EXTENSIONS}" ]]; then
CREATE_CMD=""
for EXTENSION in ${NEW_DB_EXTENSIONS[@]}; do
CREATE_CMD="$CREATE_CMD CREATE EXTENSION IF NOT EXISTS \"${EXTENSION}\";"
done
psql -abe "$PG_URL_NEWDB" -c "${CREATE_CMD}";
fi
fi
if [[ -n $(psql -qtA -c "\du ${NEW_USER_BASE}" | cut -d "|" -f 1) ]]; then
echo "User already exist, skip creation"
else
echo "Creating user ${NEW_USER_BASE} on ${PGHOST}"
psql -abe "$PG_URL_ADMIN" -c "CREATE USER \"$NEW_USER_BASE\""
fi
echo "Set password for user ${NEW_USER_BASE}"
psql -abe "ALTER USER \"$NEW_USER_BASE\" WITH PASSWORD '$NEW_PASSWORD';"
echo "Grant user \"${NEW_USER_BASE}\" to \"${PGUSER%%@*}\""
psql -abe "$PG_URL_ADMIN" -c "
GRANT \"$NEW_USER_BASE\" to \"${PGUSER%%@*}\";
GRANT ALL PRIVILEGES ON DATABASE \"$NEW_DB_NAME\" TO \"$NEW_USER_BASE\";
GRANT USAGE ON SCHEMA public TO \"$NEW_USER_BASE\";
GRANT ALL ON ALL TABLES IN SCHEMA public TO \"$NEW_USER_BASE\";
GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO \"$NEW_USER_BASE\";
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO \"$NEW_USER_BASE\";
"
echo "Done"
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment