Skip to content

Instantly share code, notes, and snippets.

@lgarner
Last active October 27, 2020 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lgarner/65aad7f6a15b790f9f76 to your computer and use it in GitHub Desktop.
Save lgarner/65aad7f6a15b790f9f76 to your computer and use it in GitHub Desktop.
MongoDB admin and database user and role creation
Get MongoDB
-----------
https://www.mongodb.org/downloads
Or the apt repo based tutorial here for Ubuntu:
http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/
MongoDB *should* match the python pymongo where possible to avoid version mismatch problems.
Take note about updating the mongod.conf file to a non-local host IP if doing db replication.
Start the shell
---------------
mongo
Sanity Check
------------
db.version()
The current version of Mongo's manual is here:
http://docs.mongodb.org/manual/
Create the first MongoDB Admin user
-----------------------------------
The permissions model is based on roles. For production, be very certain to remove unneeded roles.
Admin can take additional roles, including "root", "dbAdminAnyDatabase", and "clusterAdmin".
use admin
db.createUser(
{
user: "someAdminName",
pwd: "anAdminPwd",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
db.system.users.find()
use yourDatabase
db.createUser(
{
user: "username01",
pwd: "aUsername01pwd",
roles: [
{ role: "dbOwner", db: "yourDatabase" },
{ role: "dbAdmin", db: "yourDatabase" },
{ role: "readWrite", db: "yourDatabase" }
]
}
)
use admin
db.system.users.find()
Stop MongoDB
------------
Make sure the correct mongodb server instance is started (check ps)
Linux:
sudo service mongod stop
Enable authentication
---------------------
MongoDB 3.4.2:
sudo vi /etc/mongodb.conf
MongoDB 3.0.6:
sudo vi /etc/mongod.conf
add authentication to mongod.conf:
security:
authorization: enabled
If you don't have that file, something is strange or not mongo v3.0. Check package installation.
Internal Authentication:
https://docs.mongodb.org/manual/tutorial/enable-internal-authentication/
security:
keyFile: /path/to/certificates/PSK.key
Start the server
----------------
Linux:
sudo service mongod start
Test authentication
-------------------
To connect:
mongo yourDatabase -u <username> -p
The password will be prompted so it won't show in your shell command history.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment