Starting with db01 server, I need to configure MongoDB first. The application's database should be accessed only with a user and a password.
For that, I need to run the MongoDB server without authentication. Then create a user with a password and a role for the app servers in the “lets_chat” database. I’m going to use an open-source chat application called “Let’s chat” for the app servers, and the application uses a MongoDB server.
This is the chat application’s GitHub repository:
https://github.com/sdelements/lets-chat
Setting up database
For setting up a database for the chat application, I wrote a shell script. At first, it started a MongoDB server without authentication. Then adds a user to the lets_chat database. After that, the script proceeds to enable authentication for Mongodb connections. I’m pasting the script here:
if [[ -f /opt/.mongo_db_configured ]]; then
exit 0
fi
DB_NAME="lets_chat"
DB_USER="app_user"
DB_PASSWORD=`cat /etc/lets_chat_db_password.txt`
# start the mongodb server in background
systemctl start mongod
sleep 2
# create a user for app servers in lets_chat database
mongosh lets_chat <<EOF
db.createUser({ "user": "$DB_USER", "pwd": "$DB_PASSWORD", "roles": [{ "role": "readWrite", "db": "$DB_NAME" }] })
EOF
# stop the mongodb server that is running in the background
systemctl stop mongod
# enable authentication for mongodb connection
sed -i 's/#security:/security:\
authorization: "enabled"/g' /etc/mongod.conf
touch /opt/.mongo_db_configured
I wanted the DB password hidden from everyone else. So, I created a txt file and added the DB password. Then, I encrypted the txt file using ansible-vault. The encrypted file will be in git version control. Anyone who wants to configure the db01 server must decrypt the encrypted txt file.
After setting up the database, I created a file (/opt/.mongo_db_configured)
in the db01 server. The shell script checks if this file exists or not. If it exists, that means the database has been configured already, no need to re-configure.
After running this shell script through ansible-playbook
command, another playbook task takes care of starting and enabling the mongod service.
What’s next
I will be configuring the app servers. Stay tuned for more upcoming devlogs.