-
Notifications
You must be signed in to change notification settings - Fork 0
/
init_db.sh
59 lines (49 loc) · 1.62 KB
/
init_db.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/bin/bash
# Immediately exits if any error occurs during the script
# execution. If not set, an error could occur and the
# script would continue its execution.
set -o errexit
# Creating an array that defines the environment variables
# that must be set. This can be consumed later via arrray
# variable expansion ${REQUIRED_ENV_VARS[@]}.
readonly REQUIRED_ENV_VARS=(
"MFL_DB_USER"
"MFL_DB_PASSWORD"
"MFL_DB_DATABASE"
"POSTGRES_USER")
# Main execution:
# - verifies if all environment variables are set
# - runs the SQL code to create user and database
main() {
check_env_vars_set
init_user_and_db
}
# Checks if all of the required environment
# variables are set. If one of them isn't,
# echoes a text explaining which one isn't
# and the name of the ones that need to be
check_env_vars_set() {
for required_env_var in ${REQUIRED_ENV_VARS[@]}; do
if [[ -z "${!required_env_var}" ]]; then
echo "Error:
Environment variable '$required_env_var' not set.
Make sure you have the following environment variables set:
${REQUIRED_ENV_VARS[@]}
Aborting."
exit 1
fi
done
}
# Performs the initialization in the already-started PostgreSQL
# using the preconfigured POSTGRE_USER user.
init_user_and_db() {
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL
CREATE USER $MFL_DB_USER WITH PASSWORD '$MFL_DB_PASSWORD';
CREATE DATABASE $MFL_DB_DATABASE;
GRANT ALL PRIVILEGES ON DATABASE $MFL_DB_DATABASE TO $MFL_DB_USER;
EOSQL
}
# Executes the main routine with environment variables
# passed through the command line. We don't use them in
# this script but now you know 🤓
main "$@"