Merge remote-tracking branch 'heliocastro/user_pass_improvement'

This commit is contained in:
Corbin Bartsch 2022-06-24 14:56:08 -04:00
commit 171052da65
Signed by: coredotbin
GPG Key ID: 32D3B80A08D93212
2 changed files with 11 additions and 7 deletions

View File

@ -18,8 +18,7 @@ mechanism.
### By mounting a volume
Clone the repository, mount its directory as a volume into
`/docker-entrypoint-initdb.d` and declare database names separated by commas in
`POSTGRES_MULTIPLE_DATABASES` environment variable as follows
`/docker-entrypoint-initdb.d` and declare database names separated by commas and each entry with database, user and password separated by double colon in `POSTGRES_MULTIPLE_DATABASES` environment variable as follows
(`docker-compose` syntax):
myapp-postgresql:
@ -27,9 +26,10 @@ Clone the repository, mount its directory as a volume into
volumes:
- ../docker-postgresql-multiple-databases:/docker-entrypoint-initdb.d
environment:
- POSTGRES_MULTIPLE_DATABASES=db1,db2
- POSTGRES_MULTIPLE_DATABASES=db1:user:pwd,db2:user:pwd
- POSTGRES_USER=myapp
- POSTGRES_PASSWORD=
- POSTGRES_DB=db
### By building a custom image
@ -48,10 +48,11 @@ to the container:
- POSTGRES_MULTIPLE_DATABASES=db1,db2
- POSTGRES_USER=myapp
- POSTGRES_PASSWORD=
- POSTGRES_DB=db
### Non-standard database names
If you need to use non-standard database names (hyphens, uppercase letters etc), quote them in `POSTGRES_MULTIPLE_DATABASES`:
environment:
- POSTGRES_MULTIPLE_DATABASES="test-db-1","test-db-2"
- POSTGRES_MULTIPLE_DATABASES="test-db-1:user:pwd","test-db-2:user:pwd"

View File

@ -4,12 +4,15 @@ set -e
set -u
function create_user_and_database() {
local database=$1
local dbinfo=$1
IFS=":" read -r database user password <<< "$dbinfo"
echo " Creating user and database '$database'"
echo "Creating database '$database' with user '$user' and password '$password'"
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "postgres" <<-EOSQL
SELECT 'CREATE USER ' || LOWER(TRIM('$database')) AS create_user_query WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = LOWER(TRIM('$database')));\gexec
SELECT 'CREATE USER ' || LOWER(TRIM('$user')) AS create_user_query WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = LOWER(TRIM('$user')));\gexec
ALTER USER $user WITH ENCRYPTED PASSWORD '$password';
SELECT 'CREATE DATABASE ' || LOWER(TRIM('$database')) || ' WITH OWNER "$POSTGRES_USER" ENCODING "UTF8" LC_COLLATE = "en_US.UTF-8" LC_CTYPE = "en_US.UTF-8" TEMPLATE="template0"' AS create_table_query WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = LOWER(TRIM('$database')));\gexec
GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
GRANT ALL PRIVILEGES ON DATABASE $database TO $user;
EOSQL
}