#
# This play expects PyMongo to be installed locally.  You need to provide
# the hostname or IP address of one of the mongo hosts, 
#
# ansible-playbook -i localhost, create_mongo_users.yml -e@edx.yml -e@stage-edx.yml -e@db/edxapp-mongo.yml
#
# edxapp-mongo.yml should define MONGO_USERS with the following format
#
# MONGO_USERS:
#   - user: edxapp001
#     password: secret
#     database: edxapp
#     roles: readWrite
# 
# define optional MONGO_ROLES in edxapp-mongo.yml with the following format to create and use custom mongodb role
#
# MONGO_ROLES:
#   - database: edxapp
#     role: edxapp_readWrite
#     privileges: "'createCollection', 'createIndex', 'dropIndex', 'find', 'insert', 'listIndexes', 'listCollections', 'remove', 'renameCollectionSameDB', 'update'"
#
# It should also define a login_host and repl_set.  You can set login_host to
# be any member of your cluster as this code will find and connect to the
# primary.
#
# login_host: 10.17.90.123
# repl_set: prod-edx-edxapp

- name: Create mongo users
  hosts: all
  gather_facts: False
  connection: local
# This allows you to use your virtualenv's pymongo instead of installing it globally
  vars:
    ansible_python_interpreter: "/usr/bin/env python"
  tasks:
    - name: install python mongo module
      pip: name=pymongo state=present

    - name: create a mongodb role
      shell: mongo -u {{ MONGO_ADMIN_USER }} -p {{ MONGO_ADMIN_PASSWORD }} --host {{ repl_set }}/{{ login_host }} --authenticationDatabase admin --eval "db = db.getSiblingDB('{{ item.database }}');if ( db.getRole('{{ item.role }}') === null ){ db.createRole({ role{{':'}} '{{ item.role }}', privileges{{':'}} [{ resource{{':'}} { db{{':'}} '{{ item.database }}', collection{{':'}} '' }, actions{{':'}} [{{ item.privileges }}]}], roles{{':'}} []}); } else { db.updateRole('{{ item.role }}',{ privileges{{':'}} [{ resource{{':'}} { db{{':'}} '{{ item.database }}', collection{{':'}} '' }, actions{{':'}} [{{ item.privileges }}]}], roles{{':'}} []}); }"
      with_items: "{{ MONGO_ROLES }}"
      when: MONGO_ROLES is defined

    - name: create a mongodb user
      mongodb_user:
        database: "{{ item.database }}"
        login_user: "{{ MONGO_ADMIN_USER }}"
        login_password: "{{ MONGO_ADMIN_PASSWORD }}"
        login_host: "{{ login_host }}"
        name: "{{ item.user }}"
        password: "{{ item.password }}"
        roles: "{{ item.roles }}"
        state: present
        replica_set: "{{ repl_set }}"
      with_items: "{{ MONGO_USERS }}"
