There is a replica set without authentication. I want to create its authentication for first time.
I do as following:
1- create [administrator user][1]
2- restarting all member with option `auth=true`
3- login as aadministrator to one member of replica set
4- trying to create user "db.addUser(...)"
but when I want to create user, it throw exception of couldn't add user: not master at src/mongo/shell/db.js:128
What should I do? is it possible initiate security in existing replica set Or I should, remove replica set and rebuild it, after setting authentication.
If replica set already exists, you need to find the primary node, add a user with "root" role, and for each database add a user with admin/writeAndRead/read role, and/or add an admin user for all databases.
use admin
db.createUser({ user: "rootUser", pwd: "rootPass", roles: [ { role: "root", db: "admin" } ] })
db.createUser({ user: "admin", pwd: "adminPass", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })
use otherDb
db.createUser({ user: "rwUser", pwd: "rwUserPass", roles: [{ role: "readWrite", db: "otherDb" }] })
Wait until sync all replica nodes. Set auth=yes on each mongod.conf file (this will force each client to use user/pass).
If you want (not required), to add keyFile to enforce extra security steps between all replica set, you can create this file, copy between each node and enable keyFile option inside each mongod.conf file, but this is only to force replica set nodes to know a secret between them and start talking, not for client applications.
Finally restart the primary node wait for new primary election and continue restarting all nodes inside replica set.
Couple of useful links for create secret key file http://docs.mongodb.org/v2.6/tutorial/deploy-replica-set-with-auth/#create-the-key-file-to-be-used-by-each-member-of-the-replica-set and more details for the mongodb v2.6 version http://docs.mongodb.org/v2.6/tutorial/deploy-replica-set-with-auth/#create-the-key-file-to-be-used-by-each-member-of-the-replica-set
though replica set exists, it is not a master or master has not set. you might haven't init replica set yet.
https://docs.mongodb.com/manual/tutorial/deploy-replica-set/
> rs.initiate()
> rs.add("secondary-host:27017")
> rs.add("more-hosts-if-exist:27017")
and then you could create user.
> db.createUser({ user: "root", pwd: "rootpw", roles: [ { role: "root", db: "admin" } ] })
> db.createUser({user: "useradmin", pwd: "adminpw", roles: [ { role: "userAdmin", db: "admin" } ] })
like @Aaron Castro's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With