Securing a Replica Set (KeyFile)
Step-by-step guide to securing a MongoDB replica set using Keyfiles.
This page describes how to setup a Keyfile authentication between members of a replica set.
This guide is for new instances only where no uptime is required. If you want to secure your MongoDB replica set with keyfiles without downtime, see the official documentation.
Generate a keyfile
In this guide, we’ll secure the replica set using a shared keyfile.
To generate a keyfile, run the following command on the first node:
openssl rand -base64 756 > keyfile
chmod 400 keyfilePlace this keyfile in the $MONGO_BASE/admin/$MONGO_INSTANCE/secret directory and copy it to all nodes in the replica set.
On the PRIMARY node, create a dmk user that will be used by the DMK to connect to the instances.
Connect to the PRIMARY node with ms, and run the following commands :
use admin
db.createUser({user:"dmk", pwd:passwordPrompt(), roles:[{role:"root", db:"admin"}]})Example:
mongodb@vm00:/home/mongodb/ [mdbrs01] ms
test> use admin
switched to db admin
admin> db.createUser({user:"dmk", pwd:passwordPrompt(), roles:[{role:"root", db:"admin"}]})
Enter password
{ ok: 1 }In the $MONGO_BASE/admin/$MONGO_INSTANCE/secret directory, create a cred.yaml file where the credentials will be stored.
Change the permissions with chmod 400 cred.yaml. You can now test the credentials with the msp alias.
Stop all nodes, starting with SECONDARY nodes
SECONDARY nodesStop all nodes with mgstop, starting with the secondary nodes. At the end of this step, all members of the replica set should be offline.
Update MongoDB configuration files
On all three nodes, modify the configuration file to include the security.authorization and security.keyFile parameters:
Restart all nodes
You can now restart all nodes, starting with the PRIMARY.
Connect on the primary node with the msp alias, and check the status of the replica set with rs.status(), or directly run the rsta alias :
You have successfully secured a MongoDB replica set using Keyfiles.
Last updated