felt/mongodb/db_init.sh

41 lines
1.2 KiB
Bash
Raw Permalink Normal View History

#!/bin/bash
set -e
# dbUser is the userName used from applicatoin code to interact with databases and dbPwd is the password for this user.
# MONGO_INITDB_ROOT_USERNAME & MONGO_INITDB_ROOT_PASSWORD is the config for db admin.
# admin user is expected to be already created when this script executes. We use it here to authenticate as admin to create
# dbUser and databases.
echo ">>>>>>> trying to create database and users"
if [ -n "${MONGO_INITDB_ROOT_USERNAME:-}" ] && [ -n "${MONGO_INITDB_ROOT_PASSWORD:-}" ] && [ -n "${dbUser:-}" ] && [ -n "${dbPwd:-}" ]; then
mongosh -u $MONGO_INITDB_ROOT_USERNAME -p $MONGO_INITDB_ROOT_PASSWORD<<EOF
// create DB
db=db.getSiblingDB('felt');
use felt;
if (db.system.users.find({user:'$dbUser'}).count()) {
return;
}
// Create user account the API uses to connect to db
db.createUser({
user: '$dbUser',
pwd: '$dbPwd',
roles: [{
role: 'readWrite',
db: 'felt'
}]
});
// Insert default config options
db.config.insertOne({
_immutable: true
});
EOF
else
echo "MONGO_INITDB_ROOT_USERNAME,MONGO_INITDB_ROOT_PASSWORD,dbUser and dbPwd must be provided. Some of these are missing, hence exiting database and user creation"
exit 403
fi