mongodb

How to reset mongodb root password in a replica set configuration?


I was following some how-to, but I always get the following erro. How to reset the admin (root role) password when running a replica set in mongodb?

The steps was:

Stop all mongodb instances in the replica set

start one mongo instance as

mongod --dbpath /var/lib/mongo --port 27017 --bind_ip localhost
--replSet rs0 --fork --logpath /var/log/mongodb/mongod.log

Connect to the instance and change the password:

use admin
db.updateUser("root", {pwd: "test123"});

But I always get the error

admin> db.updateUser("root", {pwd: "test123"});
MongoServerError[NotWritablePrimary]: not primary

Solution

  • The "official" way is like this:

    Be aware, while member runs with --transitionToAuth everybody may connect without credentials and gain full root privileges.

    However, there is a much simpler way of doing it. Simply use the internal credentials, i.e. the security.keyFile to connect. Would be this one:

    mongosh "mongodb://localhost:27017/?authSource=local" -u __system -p "$(tr -d '\011-\015\040' < path-to-keyfile)"
    

    tr -d '\011-\015\040' is only needed if your keyfile contains any new-line characters.

    If you use x.509 certificates for internal membership authentication, it works in the same way. Simply use the server net.tls.clusterFile to connect.