Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add user to mongodb via python

I want to be able to add users to MongoDB so that we can automate MongoDB installs with authentication already baked in. I can successfully add users using pymongo that are read only or are dbOwner by doing this:

from pymongo import MongoClient

client = MongoClient('localhost:27017')   
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', True)

but when I do this following code block to specify roles, it fails:

from pymongo import MongoClient

client = MongoClient('localhost:27017')
client.admin.authenticate('siteRootAdmin', 'Test123')
client.testdb.add_user('newTestUser', 'Test123', False, 'readWrite')

with the error:

line 10, in <module>
    client.admin.add_user('newTestUser', 'Test123', False, 'readWrite')
TypeError: add_user() takes at most 4 arguments (5 given)

In the docs it implies that you are able to have optional fields for the user document such as other roles. Has anyone been able to set these correctly? Namely, I want to have readWrite service accounts that can add data to collections but don't have full dbOwner privileges.

like image 403
rhealitycheck Avatar asked Jul 10 '14 21:07

rhealitycheck


2 Answers

Here is the workaround:

client.testdb.add_user('newTestUser', 'Test123', roles=[{'role':'readWrite','db':'testdb'}])

Note: as you're going to set "roles", should leave the 3rd argument (read_only) empty.

like image 179
ZZY Avatar answered Sep 21 '22 18:09

ZZY


Starting from version 3 add_user is deprecated and will be removed in later versions. It cause following warning when called:

DeprecationWarning: add_user is deprecated and will be removed in PyMongo 4.0. Use db.command with createUser or updateUser instead

Above code might be rewritten to

client.testdb.command(
    'createUser', 'newTestUser', 
    pwd='Test123',
    roles=[{'role': 'readWrite', 'db': 'testdb'}]
)

like image 31
em2er Avatar answered Sep 20 '22 18:09

em2er