Skip to content

Instantly share code, notes, and snippets.

@xandout
Created December 15, 2020 18:58
Show Gist options
  • Save xandout/61d25df23a77236ab28236650f84ce6b to your computer and use it in GitHub Desktop.
Save xandout/61d25df23a77236ab28236650f84ce6b to your computer and use it in GitHub Desktop.
MongoDB User Management

MongoDB User Management

This is a simple script that will keep the database users in sync with a defined JSON document.

My ultimate use case is in a K8S environment so the files will be templated and I will add and remove users from my databases that way.

This is the test rig and shows how to manage the creation, updating and deletion of MongoDB users.

Parts

  • docker-compose.yml - Starts containers
  • env_file - Contains the environment variables
  • mongo-user.py - The code
  • requirements.txt - The python requirements
  • users.json - A simple JSON document the python script reads to handle the users

Running

docker-compose up -d mongo
sleep 5
docker-compose up script

Adding & Updating Users

Add a new item to the mongo_users key in users.json or change the password or roles.

Removing a User

Remove the user object from mongo_users in users.json

version: "2.4"
services:
mongo:
image: bitnami/mongodb:4.4-debian-10
restart: on-failure
env_file:
- env_file
networks:
- main
script:
depends_on:
- mongo
image: python:3
env_file:
- env_file
volumes:
- ./mongo-user.py:/mongo-user.py
- ./users.json:/users.json
- ./requirements.txt:/requirements.txt
entrypoint:
- /bin/bash
- '-c'
- |
pip install --no-cache-dir -r /requirements.txt
python /mongo-user.py
networks:
- main
networks:
main:
BITNAMI_DEBUG=false
MONGODB_USERNAME=regularuser
MONGODB_DATABASE=mydatabase
MONGODB_PASSWORD=regularpass
MONGODB_ROOT_PASSWORD=pootrass
MONGODB_URI=mongodb://root:pootrass@mongo/mydatabase?authSource=admin
import os
import json
from pymongo import MongoClient
import pymongo
mongouri = os.getenv("MONGODB_URI")
targetDb = os.getenv("MONGODB_DATABASE")
json_data = None
with open('/users.json') as f:
json_data = json.load(f)
client = MongoClient(mongouri)
for user in json_data['mongo_users']:
try:
client[targetDb].command("createUser", user['name'], pwd=user['password'], roles=user['roles'])
print(f"Created user {user['name']}")
except pymongo.errors.OperationFailure as e:
if e.code == 51003: # Duplicate user error code pymongo.errors.OperationFailure: User "jdoe@mydatabase" already exists, full error: {'ok': 0.0, 'errmsg': 'User "jdoe@mydatabase" already exists', 'code': 51003, 'codeName': 'Location51003'}
print(f"User {user['name']} exists, updating")
client[targetDb].command("updateUser", user['name'], pwd=user['password'], roles=user['roles'])
existing_users = [x['user'] for x in client[targetDb].command('usersInfo')['users']]
wanted_users = [x['name'] for x in json_data['mongo_users']]
remove_users = list(set(existing_users) - set(wanted_users))
for user in remove_users:
print(f"Removing {user}")
client[targetDb].command("dropUser", user)
{
"mongo_users": [
{
"name": "jdoe",
"password": "blah",
"roles": [
{
"role": "readWrite",
"db": "mydatabase"
}
]
},
{
"name": "regularuser",
"password": "regularpass",
"roles": [
{
"role": "readWrite",
"db": "mydatabase"
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment