14

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.

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you! that syntax for the roles is what i was messing up. i had tried roles = 'readWrite' but didn't notice that mongodb takes both the role and the db in there.
@rhealitycheck: Actually according to the MongoDB shell syntax, "roles" should always be an array, it could also be roles=["readWrite"] as long as you make sure to run this command after selecting "testdb".
How do I get a result showing that is was successful or not?
This answer is no longer correct. add_user was deprecated in 3.6 and removed in 4.0. The replacement method command() is only available for M10 and larger clusters.
13

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'}]
)

2 Comments

This answer is correct starting with pymongo 4.0. command() is only available for M10 and larger clusters.
Hey @em2er - can you see why your answer is not working for me in this question: stackoverflow.com/q/76428469/539223

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.