Created
April 17, 2024 15:33
-
-
Save cerealkill/36ebebf249b8bc8bfe00af7e349f8bed to your computer and use it in GitHub Desktop.
Create Postgres roles and users in init from .env files variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
set -u | |
function create_user_and_database() { | |
if psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" -tXAc "SELECT 1 FROM pg_roles WHERE rolname='$POSTGRES_USER'"; then | |
echo Roles already exist, skipping creation. | |
else | |
echo Running SQL commands | |
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL | |
CREATE USER $POSTGRES_USER WITH PASSWORD '$POSTGRES_PASSWORD'; | |
CREATE DATABASE $POSTGRES_DB; | |
GRANT ALL PRIVILEGES ON DATABASE $POSTGRES_DB TO $POSTGRES_USER; | |
EOSQL | |
echo Done! | |
fi | |
} | |
echo Creating DB roles... | |
create_user_and_database |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment