Skip to content

Commit 6151b43

Browse files
committed
Simple script improvement to add the capability of different user and password per database entry
Signed-off-by: Helio Chissini de Castro <[email protected]>
1 parent ac7f26d commit 6151b43

File tree

2 files changed

+14
-10
lines changed

2 files changed

+14
-10
lines changed

README.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -18,18 +18,18 @@ mechanism.
1818
### By mounting a volume
1919

2020
Clone the repository, mount its directory as a volume into
21-
`/docker-entrypoint-initdb.d` and declare database names separated by commas in
22-
`POSTGRES_MULTIPLE_DATABASES` environment variable as follows
21+
`/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
2322
(`docker-compose` syntax):
2423

2524
myapp-postgresql:
2625
image: postgres:9.6.2
2726
volumes:
2827
- ../docker-postgresql-multiple-databases:/docker-entrypoint-initdb.d
2928
environment:
30-
- POSTGRES_MULTIPLE_DATABASES=db1,db2
29+
- POSTGRES_MULTIPLE_DATABASES=db1:user:pwd,db2:user:pwd
3130
- POSTGRES_USER=myapp
3231
- POSTGRES_PASSWORD=
32+
- POSTGRES_DB=db
3333

3434
### By building a custom image
3535

@@ -48,10 +48,11 @@ to the container:
4848
- POSTGRES_MULTIPLE_DATABASES=db1,db2
4949
- POSTGRES_USER=myapp
5050
- POSTGRES_PASSWORD=
51+
- POSTGRES_DB=db
5152

5253
### Non-standard database names
5354

5455
If you need to use non-standard database names (hyphens, uppercase letters etc), quote them in `POSTGRES_MULTIPLE_DATABASES`:
5556

5657
environment:
57-
- POSTGRES_MULTIPLE_DATABASES="test-db-1","test-db-2"
58+
- POSTGRES_MULTIPLE_DATABASES="test-db-1:user:pwd","test-db-2:user:pwd"

create-multiple-postgresql-databases.sh

+9-6
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,15 @@ set -e
44
set -u
55

66
function create_user_and_database() {
7-
local database=$1
8-
echo " Creating user and database '$database'"
9-
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
10-
CREATE USER $database;
11-
CREATE DATABASE $database;
12-
GRANT ALL PRIVILEGES ON DATABASE $database TO $database;
7+
local dbinfo=$1
8+
IFS=":" read -r database user password <<< "$dbinfo"
9+
10+
echo "Creating database '$database' with user '$user' and password '$password'"
11+
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
12+
CREATE USER $user;
13+
ALTER USER $user WITH ENCRYPTED PASSWORD '$password';
14+
CREATE DATABASE $database;
15+
GRANT ALL PRIVILEGES ON DATABASE $database TO $user;
1316
EOSQL
1417
}
1518

0 commit comments

Comments
 (0)