0

I am trying setup a mongoDB RepSet with python, I have 2 replicas connected, but I can not figure out how to create the first admin user use pymongo.

I know I can create first Admin user using mongo shell as follow

db.getSiblingDB("admin").createUser({
      user : "main_admin",
      pwd  : "abc123",
      roles: [ { role: "root", db: "admin" } ]
 });

After create an admin user with mongo shell, I have no problem to use this python line client.testdb.add_user('newTestUser', 'Test123', roles=[{'role':'readWrite','db':'testdb'}]) to create a user.

But, is there a way to create the first admin user with pymongo?

Notes:

Command to start mongod:

mongod --bind_ip 0.0.0.0 --replSet MainRepSet --auth --clusterAuthMode keyFile \
       --keyFile /etc/secrets-volume/internalAuthMongoDBKeyfile --setParameter authenticationMechanisms=SCRAM-SHA-1  > /tmp/log &

python code for creating rs

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
conf = {'_id': "MainRepSet", 'members': [
       { '_id': 0, 'host' : "operations-mongo-0.operations-    mongo.governor.svc.cluster.local:27017" },
       { '_id': 3, 'host' : "operations-mongo-3.operations-    mongo.governor.svc.cluster.local:27017" }
]}
client.admin.command("replSetInitiate",conf)
Yang
  • 828
  • 6
  • 22

1 Answers1

0

I'm sure you can't do that just with pymongo. You could use either os or subprocess modules along with pymongo.

You would to start mongod without auth enabled, create your user, shutdown mongo and then restart with auth enabled:

Presuming your were running on the localhost, something like:

from subprocess import call
from pymongo import MongoClient

call(["mongod", "-f mongoNonAuth.conf"])

client = MongoClient('localhost', 27017)
db = client["admin"]

db.command("createUser", "admin", pwd="password", roles=["root"])
db.command("shutdown")

call(["mongod", "-f mongoAuth.conf"])

client = MongoClient('localhost', 27017, 
         username="user name", password="pass/word")

Please note: Above code not tested

More info on subprocess vs osCalling an external command in Python