Authenticate mongodb replica set - mongodb

I have 4 instances of mongodb running(replica set) with following mongodb.conf file for each instance:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /root/mongodata/log/mongod.log
# Where and how to store data.
storage:
dbPath: /root/mongodata/db1 # also have db2 and so on for rest of the instances
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# how the process runs
processManagement:
fork: true # fork and run in background
pidFilePath: /root/mongodata/db1/mongod.pid # location of pidfile, different for 4 instances
# network interfaces
net:
port: 30000 #port different for 4 different instances
bindIp: 12.123.321.432(example ip, same for all 4 .conf files)
# security
security:
KeyFile: /path to my keyfile location
# authorization: enabled
#operationProfiling:
replication:
replSetName: testReplica #have this same for all 4
#sharding:
## Enterprise-Only Options
#auditLog:
#snmp:
I also created a keyfile for internal authentication as follows:
openssl rand -base64 756 > <path-to-keyfile>
chmod 400 <path-to-keyfile>
After all the instances are running I opened mongoShell as follows:
mongo --host 12.123.321.432 --port 30000
I am able to open the shell but when I try to create a user, I get the following exception:
2016-12-22T20:55:38.396-0500 E QUERY [thread1] Error: couldn't add user: not authorized on test to execute command { createUser: "root", pwd: "xxx", roles: [ { role: "root", db: "admin" } ], digestPassword: false, writeConcern: { w: "majority", wtimeout: 30000.0 } } :
_getErrorWithCode#src/mongo/shell/utils.js:23:13
DB.prototype.createUser#src/mongo/shell/db.js:1230:11
#(shell):1:1
I tried switching to admin db but still says unauthorized, I also tried to run rs.initiate() command to define primary and secondary dbs, says unauthorized. I read even if i start the mongod with authentication disabled the internal authentication via keyfile will force the role based authentication. What am I missing here and how would i resolve it? thanks in advance.

The error message shows that you have not privileges to execute the command.
After set keyfile parameter in .conf file, mongo need you login with auth user.
So if you have not root user.
start mongod without auth config (don't set keyfile and disable security.authorization )
create use with root role
db.createUser({user:"root",pwd:"rootpassword",roles:[{role:"root",db:"admin"}]})
if you have root user, you should use db.auth() or login mongo with root privileges, for executing rs.conf() command.
mongo --port portnumber -u root -p --authenticationDatabase admin
or after login with command mongo --port portnumber
db.auth("root", "rootpassword")
ps. KeyFile is for replica set inner communication security.

Related

MongoDB unable to connect to the newly created admin user in admin db

We have created a new admin user in mongodb version 3.6.21
[root#MONGODB01 mongodb]# mongo --port 37017
MongoDB shell version v3.6.21
connecting to: mongodb://127.0.0.1:37017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("54681232-fa6b-4dbd-bfe5-c1bde274d430") }
MongoDB server version: 3.6.21
s1:PRIMARY> use admin
switched to db admin
s1:PRIMARY> db.createUser(
... {user: "admin",
... pwd: "reco#123",
... roles:[{role: "root" , db:"admin"}]})
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "root",
"db" : "admin"
}
]
}
s1:PRIMARY> exit
bye
After that we are trying to login but facing below error. Please help
[root#MONGODB01 mongodb]# mongo --port 37017 –u admin –p reco#123 -authenticationDatabase admin
MongoDB shell version v3.6.21
connecting to: mongodb://127.0.0.1:37017/%E2%80%93u?authSource=admin&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("729e70cf-d594-4bd1-b6dc-73d75fd20f89") }
MongoDB server version: 3.6.21
loading file: admin
2021-10-18T15:35:07.305+0530 E - [main] file [admin] doesn't exist
failed to load: admin
Below is the config file for primary mongod instance.
[root#MONGODB01 mongodb]# cat /etc/mongod.conf
# mongod.conf
systemLog:
destination: file
logAppend: true
path: /data/mongodb/primary1/mongod.log
storage:
dbPath: /data/mongodb/primary1/db
journal:
enabled: true
# mmapv1:
# # Reduce data files size and journal files size
# smallFiles: true
wiredTiger:
engineConfig:
cacheSizeGB: 4
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
timeZoneInfo: /usr/share/zoneinfo
net:
port: 37017
bindIp: 0.0.0.0
security:
# authorization: enabled
keyFile: /data/mongodb/key/mongodb.key
replication:
replSetName: s1
sharding:
clusterRole: shardsvr
FYI - We are running Primary shard1, Replica Shard 2 and Replica Shard 3 on single node.
You need two hyphen --, should be this:
mongo --port 37017 --authenticationDatabase admin -u admin -p reco#123
You may enclose the password by quotes, i.e.
mongo --port 37017 --authenticationDatabase admin -u admin -p "reco#123"
For username and password you use either short or long form, i.e.
-u admin -p "reco#123"
or
--username admin --password "reco#123"
I was able to solve this issue by using below command instead
mongo --port 37017 -authenticationDatabase admin -u admin -p reco#123

Can't connect to MongoDB remote server

I have setup mongodb on a Google cloud compute instance and am trying to connect to it remotely. My mongod.conf file looks like this:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0
#processManagement:
security:
authorization: 'enabled'
I have setup a firewall rule in my Google Cloud console that tags the instance and opens tcp:27017 for ip ranges 0.0.0.0/0.
Checking on the port 27017 it looks like mongo is listening:
sudo netstat -tulpn | grep 27017
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 3781/mongod
Overall it also seems like port 27017 is open:
netstat --listen
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 *:27017 *:* LISTEN
...
On the instance I setup an admin database with admin user:
>use admin
>db.createUser(
{
user: 'admin',
pwd: 'somepass',
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
}
)
I also setup a user for a test database:
>use test
>db.createUser(
{
user: 'tester',
pwd: 'apassword',
roles: [{ role: "readWrite", db: "test" },
{ role: "read", db: "reporting" }]
}
)
This user works locally:
>use test
>db.auth('tester', 'apassword')
1
However when I try to connect remotely it fails:
$ mongo -u tester -p apassword 12.345.67.890/test
MongoDB shell version v3.4.1
connecting to: mongodb://12.345.67.890/test
2017-11-14T12:47:07.369-0700 W NETWORK [main] Failed to connect to 12.345.67.890:27017 after 5000ms milliseconds, giving up.
2017-11-14T12:47:07.370-0700 E QUERY [main] Error: couldn't connect to server 12.345.67.890:27017, connection attempt failed :
connect#src/mongo/shell/mongo.js:234:13
#(connect):1:6
exception: connect failed
I'm not a networking expert so I've pretty much exhausted my knowledge at this point and don't know how to proceed.
Am I missing something in mongod.conf? Did i setup the firewall incorrectly? Any help is appreciated.
I came up with a solution for this, but I'm unclear why it works and not my original approach.
My instance has http/https enabled. This uses the firewall rules default-allow-http and default-allow-https. These rules enable connections from anywhere (0.0.0.0/0) through tcp ports 80 and 443 respectively. I edited the http rule and added tcp port 27017.
Now I can connect to the server.
As a test, I reset the http rule and added another rule applied to all instances opening up tcp:27017 to 0.0.0.0/0. Essentially everything is the same as the http rule save for the name and the target tags. With this change I cannot connect to the server.
It seems rather strange and it doesn't feel like an intended behavior, unless my understanding of the firewall rules in incomplete.
In the end it looks like either setting up mongo to use one of the http/https ports or adding port 27017 to those rules is the way to go.

Replica - MongoDB EC2 instances

Added 3 EC2 instances in in AWS cloud.
Installed 3 MongoDB instances in 3 different instances and all are running fine.
I am adding replication for the same DBs.
below are the steps i followed:
sudo service mongod start --sslPEMKeyFile "/etc/ssl/mongodb.pem" --sslMode "requireSSL" --replSet "myReplSet" ( in all 3 mongo instances)
config = {_id : "myReplSet" , members: [{_id: 0, host:"ip-10-0-0-68:27017"},{_id: 1, host:"ip-10-0-0-247:27017"},{_id: 2, host:"ip-10-0-0-148:27017"}]}
rs.initiate(config)
Error as below:
MongoDB Enterprise > rs.initiate(config)
{
"ok" : 0,
"errmsg" : "This node was not started with the replSet option",
"code" : 76,
"codeName" : "NoReplicationEnabled"
}
EDIT
I added same security groups and Elastic IP for all 3 instances.
All 3 are new DBs.
Now I am getting error as:
{
"ok" : 0,
"errmsg" : "'ip-10-0-0-148:27017' has data already, cannot initiate set.",
"code" : 110,
"codeName" : "CannotInitializeNodeWithData"
}
EDIT-2
Config file for one the servers:
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# Where and how to store data.
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# how the process runs
processManagement:
fork: true # fork and run in background
pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile
# network interfaces
net:
port: 27017
# bindIp: 127.0.0.1,13.58.225.174,13.58.180.226 # Listen to local interface only, comment to listen on all interfaces.
#security:
#operationProfiling:
replication:
replSetName: rs0
The service start command does not accept parameters. So
sudo service mongod start --sslPEMKeyFile "/etc/ssl/mongodb.pem" --sslMode "requireSSL" --replSet "myReplSet"
Is equivalent to
sudo service mongod start
If you want to add those settings to the mongod configuration, you will need to edit /etc/mongod.conf to add them in. Since the names of some options vary between the command line and the configuration file, you should take a look at the Configuration File Options documentation to ensure you use the correct settings.
EDIT
Based on your edits and the error message, it appears the mongod process (ip-10-0-0-148:27017) already has data on it. You cannot add a mongod process that already has data to a replica set. You can, however, initiate the replica set on a mongod process that already has data. You should connect to that mongod process and run the rs.initiate() there. Then you run rs.add() to add the remaining, empty, mongod processes to the replica set.
Note: MongoDB does offer MongoDB Cloud Manager and MongoDB Atlas which can do some or all of this for you. However, they are not free, so its up to you if you want to use them.
This way it works fine.
rs.initialize()
rs.add()
rs.add()
i reffed here:
https://devops.profitbricks.com/tutorials/configure-mongodb-replica-set/

unable to launch config server for mongo shard

I am trying to get the config server running for mongo shard using the following command and config file:
mongod --config /etc/mongod2.conf
mongod2.config
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb2
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
processManagement:
pidFilePath: /srv/mongodb/db2.pid
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# network interfaces
net:
port: 27019
bindIp: 127.0.0.1
processManagement:
fork: true
#security:
# authorization: enabled
replication:
replSetName: configReplSet
sharding:
clusterRole: configsvr
When I run the command above, I get the following output (with no log output in the mongo logs):
about to fork child process, waiting until server is ready for connections.
forked process: 14246
ERROR: child process failed, exited with error number 1
I am running mongo v3.2.2 on ubuntu v14. The port 27019 is not bound by another process.
The issue was caused since I never created a separate data directory. I saw better error messages when I ran the following:
mongod --dbpath /var/lib/mongodb2 --port 27019
This command gave better error messages (it showed that the data directory was not present etc.). This helped solve the issue and I was able to run the config server (output below):
2016-06-29T12:21:30.216-0400 I CONTROL [initandlisten] MongoDB starting : pid=16060 port=27019 dbpath=/var/lib/mongodb2 64-bit host=abcdefghi
2016-06-29T12:21:30.216-0400 I CONTROL [initandlisten] db version v3.2.0

MongoDB wouldn't run as a service on Windows 7

I have the issue with running MongoDB 3.0 service in Windows 7.
I have created the data/db and data/log inside MongoDB root and configured mongod.conf file:
Edited
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: C:\Program Files\MongoDB\data\log\mongod.log
# Where and how to store data.
storage:
dbPath: C:\Program Files\MongoDB\data\db
journal:
enabled: true
# engine:
# mmapv1:
# wiredTiger:
# how the process runs
processManagement:
fork: true
pidFilePath: C:\Program Files\MongoDB\mongod.pid
# network interfaces
# net:
# port: 27017
# bindIp: 127.0.0.1 # Listen to local interface only, comment to listen on all interfaces.
#security:
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options
#auditLog:
#snmp:
Then I have created a windows service which will run the mongodb on startup:
sc.exe create MongoDB binPath= "C:\MongoDB\bin\mongod.exe
--service --config=C:\MongoDB\mongod.conf" displayname= "MongoDB 3.0 Standard"
start= "auto"
I have tried also:
sc.exe create MongoDB binPath= "\"C:\MongoDB\bin\mongod.exe\" --service --config=\"C:\MongoDB\mongod.conf\"" DisplayName= "MongoDB" start= "auto"
MongoDB service properties show me path to executable:
C:\MongoDB\bin\mongod.exe --service --config=C:\MongoDB\mongod.conf
Attempts to run service(net start MongoDB) show me error message:
The service is not responding to the control function.
More help is available by typing NET HELPMSG 2186.
I know this issue is quite popular but most of solutions led to wrong paths, file names/extensions which don't solve my problem.
UPDATE:
Suggestion to create windows service under specified user doesn't help me as well (the same message during service start):
C:\Users\Administrator>sc.exe create MongoDB binPath= "C:\MongoDB\bin\mongod.exe
--service --config=C:\MongoDB\mongod.conf" displayname= "MongoDB 3.0 Standard"
start= "auto" obj= ".\Administrator" password= "#gdgsfg1"
Moreover, I have tried to specify username and password via services.msc -> MongoDB -> Properties->Log on
Windows Event log:
Error 6.05.2015 19:54:25 Service Control Manager 7009 None
A timeout was reached (30000 milliseconds) while waiting for the MongoDB service to connect.
Error 6.05.2015 19:54:25 Service Control Manager 7000 None
The MongoDB service failed to start due to the following error:
The service did not respond to the start or control request in a timely fashion.
I have found the solution why MongoDB service doesn't start successfully.
First of all, install windows mongodb service by this way to see all kind of errors with your YAML config file or anything else during service install(sc.exe doesn't provide enough ifnormation during mongodb service install):
mongod.exe --config "C:\Program Files\MongoDB\mongod.cfg" --install
Actually, my issue was with processManagement.fork option which is not exist in Windows since it causes error Unrecognized processManagement.fork option. So, I have remove this option from my config file and service starts fine.
The final config file:
systemLog:
destination: file
logAppend: true
path: C:\Program Files\MongoDB\data\log\mongod.log
timeStampFormat: iso8601-utc
storage:
dbPath: C:\Program Files\MongoDB\data\db
journal:
enabled: true
processManagement:
pidFilePath: C:\Program Files\MongoDB\mongod.pid
net:
port: 27017
bindIp: 127.0.0.1