vidyak
vidyak

Reputation: 183

Shell script for mongo DB authentication

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'

Upvotes: 2

Views: 4097

Answers (2)

Namah
Namah

Reputation: 79

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"}]})'

Upvotes: 1

profesor79
profesor79

Reputation: 9473

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!

Upvotes: 3

Related Questions