How to create a mongoDB user using Powershell?

I am trying to write a script that creates a user in a admin

mongoDB 3.0 replica set database .

After reading many times and many tries using different versions of c-sharp MongoDB drivers, I was finally able to put together the following code that can successfully register a replica set, access the database admin

, write output the full collection name system

:

try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Driver.Core.dll'
    Add-Type -Path 'E:\drivers\MongoDB-CSharpDriver-2.0.2\MongoDB.Bson.dll'

    $connectionString = "mongodb://username:password@primary:27017,secondary:27017,arbiter:27017/admin?replicaSet=name&authSource=admin"
    $dbName =  "admin"
    $collectionName =  "System"

    function Get-MongoDBDatabase ($connectionString, $db) {
        $mongoClient = New-Object MongoDB.Driver.MongoClient($connectionString)
        $mongoServer = $mongoClient.GetServer()
        $mongoServer.GetDatabase($db)
    }

    [MongoDB.Driver.MongoDatabase] $mongoDatabase = Get-MongoDBDatabase $connectionString $dbName
    [MongoDB.Driver.MongoCollection] $mongoCollection = $mongoDatabase.GetCollection($collectionName)

    Write-Output "Test accessing collection: $($mongoCollection.FullName)"
}
catch {
    Write-Output "Error: $($_.Exception.Message)" 
}

      

At this point, I don't know which direction to go in order to create a new user in the database admin

and assign multiple roles to this user.

db.createUser( 
β€― β€―{ 
β€― β€― β€―user: "testUser", 
β€― β€― β€―pwd: "abc123", 
β€― β€― β€―roles: [β€― 
β€― β€― β€― β€― {role:"read", db:"admin"},β€― 
β€― β€― β€― β€― {role:"readWrite", db:"databaseOne"}, 
β€― β€― β€― β€― {role:"readWrite", db:"databaseTwo"}, 
β€― β€― β€― β€― {role:"readWrite", db:"databaseThree"}, 
β€― β€― β€― β€― {role:"readWrite", db:"databaseFour"}, 
β€― β€― β€― β€― {role:"read", db:"config"}] 
β€― β€―} 
)

      

Above is the command / query I would like to execute on the database admin

, but I need your help to figure out how to translate this to Powershell using MongoDB C-Sharp Driver v.2.0.2

+3


source to share


1 answer


Ok I found a way to make this work, alas, not entirely in Powershell.

Following @PeteGarafano's suggestion, I decided to use the latest and greatest driver (version 2.4.3.23 downloaded via NuGet) in a simple Visual Studio class library.

Since this is just a test at the moment, the code is very crude and filled with hardcoded things (like roles that should be assigned to the user)

Here is the class library code:

using System;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;

namespace MongoDBUtilities
{
    public class Connectivity
    {
        public bool DoesUserExist(string connectionString, string databaseName, string username)
        {
            try
            {
                var command = @" { usersInfo: { user: '" + username + @"', db: 'admin' } } ";

                var result = runCommand(connectionString, databaseName, command);
                var users = result["users"];
                if(users != null) 
                {
                    var usersArray = users.AsBsonArray;
                    if(usersArray.Count > 0) {
                        return true;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public string CreateUser(string connectionString, string databaseName, string username, string password)
        {
            try
            {
                var command = @"{ 
                      createUser: '" + username + @"',
                      pwd: '" + password + @"',
                      roles: [
                          { role: 'read', db: 'admin'},β€― 
                          { role: 'read', db: 'someDB'},β€― 
β€― β€― β€―                     { role: 'read', db: 'someOtherDB'}] 
                    }";

                var result = runCommand(connectionString, databaseName, command);
                return result.ToJson().ToString();
            }
            catch (Exception ex) {
                return unfoldException(ex);
            }
        }

        private BsonDocument runCommand(string connectionString, string databaseName, string command)
        {
            var database = getDatabase(connectionString, databaseName);
            var task = database.RunCommandAsync<BsonDocument>(command);
            var result = task.Result;
            return result;
        }

        private IMongoDatabase getDatabase(string connectionString, string databaseName) {
            IMongoClient client;
            client = new MongoClient(connectionString);
            return client.GetDatabase(databaseName);
        }

        private string unfoldException(Exception ex) {
            string message = ex.Message + Environment.NewLine;
            Exception currentException = ex;
            while (currentException.InnerException != null)
            {
                currentException = currentException.InnerException;
                message += currentException.Message + Environment.NewLine;
            }
            return message;
        }
    }
}

      

Nothing fancy, but the main thing is how you can use the JSON form of any command as described in the official MongoDB reference documentation (for example: https://docs.mongodb.com/manual/reference/command/usersInfo/ ).



NOTE . There is another way to do this by constructing objects BsonDocument

, but I found it less intuitive since the link uses all the JSON syntax.

Then I used this library in my PS script. Here's an example:

try {
    Set-ExecutionPolicy Unrestricted
    Add-Type -Path 'E:\drivers\MongoDB\MongoDBUtilities.dll'

    $connectionString = "mongodb://username:password@primaryServerName:27017,secondaryServerName:27017,arbiterServerName:27017/admin?replicaSet=replicaSetName&authSource=admin"
    $conn = New-Object -TypeName MongoDBUtilities.Connectivity
    if($conn.DoesUserExist($connectionString, "admin", "testUser")) {
        Write-Output "User already exists, no need to create again"
    }
    else {
        Write-Output "Creating user...";
        $result = $conn.CreateUser($connectionString, "admin", "testUser", "test")
        Write-Output $result;
    }
}
catch {
    Write-Output "Error: $($_.Exception.Message)" 
}

      

This example first checks to see if the user is already in the database admin

and, if it doesn't already exist, it creates it.

Hopefully this can be helpful for anyone trying to do something like this, either in C # or Powershell.

0


source







All Articles