Mongodb – 3 Node mongo db authentication setup fails

mongodb

I have 3 node mongodb replica set as below

Primary node Secondary node Arbiter node

Replication set is enabled for all three. I am trying to set up authentication for these nodes and i followed the below steps to configure it.

Step 1: Created a root user, added him to role: root with password in the primary node

Step 2: Created a key file using the command – openssl rand -base64 741 > mongodb.key in the primary node and copied the key file to all the 3 nodes

Step 3: Added the below configuration to all three nodes.

Security: authorization: enabled keyFile: /pathtokeyfile

Step 4: sudo service mongod restart, on all three nodes

After completing above steps i tried accessing the DB with username and password in the primary node and i could read the DB and files

When i try the same in secondary and arbiter nodes i get the below error

rsss0:SECONDARY> show dbs
2019-03-06T09:10:40.884+0000 E QUERY [thread1] Error: listDatabases failed:{
"operationTime" : Timestamp(1551863438, 9),
"ok" : 0,
"errmsg" : "not master and slaveOk=false",
"code" : 13435,
"codeName" : "NotMasterNoSlaveOk",
"$clusterTime" : {
"clusterTime" : Timestamp(1551863438, 9),
"signature" : {
"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
"keyId" : NumberLong(0)
}
}
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:67:1
shellHelper.show@src/mongo/shell/utils.js:860:19
shellHelper@src/mongo/shell/utils.js:750:15
@(shellhelp2):1:1

Best Answer

As shown in your question you are now connected with the secondary node. Since secondary may contain stale data, by default MongoDB won't allow you to read any data from secondary. There are two options to read your data

  1. Connect primary node (use the correct port number )

  2. From secondary, run rs.slaveOk(). This will allow you to read data from the secondary.

Note: run rs.status() or rs.isMaster() to find out which one is primary.