2
votes

I am new to shell scripting. Below is the script I have written to enable mongoDB authentication and to create users in MongoDB. When I try to connect to DB after the script execution, connection and command execution on mongo shell happens without authentication and in admin db I can see all the users are added properly. Tried killing process and starting with --auth option also but no luck. I am executing this on Ububtu 14.0 LTS. Please suggest me right approch to make this script working

#!/bin/bash
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo deb http://repo.mongodb.org/apt/ubuntu $(lsb_release -sc)/mongodb-org/3.0 multiverse | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list
sudo apt-get -y update
sudo apt-get install -y mongodb-org
cd /
sudo mkdir data
cd data
sudo mkdir db
echo "db.createUser( { user:'admin' , pwd:'password',roles: [ { role: '__system', db: 'admin' } ]})" | sudo mongo admin
echo "db.auth('admin','password')" | sudo mongo admin
sudo sh -c 'echo "security  \n  authorization : enabled" >> /etc/mongod.conf'
sudo service  mongod  restart
echo "db.createUser( { user: 'userA', pwd: 'passwordA',roles: [ { role:      'dbOwner', db: 'ManagementStore' } ]})" | sudo mongo admin  -u 'admin' -p 'password'
echo "db.createUser( { user: 'userB', pwd: 'passwordB',roles: [ { role: 'dbOwner', db: 'UserStore' } ]})" |  sudo mongo admin -u 'admin' -p 'password'
2
where are you starting mongod process?profesor79
After installation it automatically gets started. As I could see on shell, process starts to listen on port 27017vidyak
when you execute "echo "db.createUser( { user:'admin'..." are you getting any output in console? Just wondering if mongo is started when you are echoing commands?profesor79
You are right I was getting connection refused error for executing commands immediately.So after installation I had applied sleep time of 5 mins before executing any command. Forgot to add that in posted script code. and even after restart I had applied same sleep time.vidyak

2 Answers

3
votes

According to this source: you can also evaluate a command using the --eval flag, if it is just a single command

mongo --eval 
     "db.createUser( { user:'admin' , pwd:'password'... } ]})"

And check comments there as there is a lot of nice stuff too. Have a fun!

0
votes

I just noticed one thing. Not sure if that would solve the problem but, When you're enabling authentication:

sudo sh -c 'echo "security  \n  authorization : enabled" >> /etc/mongod.conf'

You seemed to have missed a colon there.:

sudo sh -c 'echo "security:\n  authorization : enabled" >> /etc/mongod.conf'

And as for createUser. I tried @profesor79's solution:

mongo --eval 'db.createUser({user: "<username>", pwd: "<password>", roles:[{ role: "root", db: "admin"}]})'