Repository: ansible/ansible-modules-extras

Issue:
mongodb_user always says changed
##### Issue Type: Bug Report
##### Plugin Name: database/misc/mongodb_user
##### Ansible Version: 2.0.0.2
##### Plugin Version: 8d86666 on 1 Dec 2015
##### Ansible Configuration:

Nothing
##### Environment:

N/A
##### Summary:

When i execute twice time the plugin, he always say the plugin has changed something.
Even with update_password=on_create
##### Steps To Reproduce:

```

---
- mongodb_user: login_user={{ mongodb3_admin_user }} login_password={{ mongodb3_admin_password }} login_port={{ mongodb3_mongos_port }} login_database=admin database={{ item.db }} name={{ item.name }} password={{ item.passwd }} roles={{ item.roles | join(",") }} state=present update_password=on_create
  with_items: mongodb3_users
  run_once: true

- mongodb_user: login_user={{ mongodb3_admin_user }} login_password={{ mongodb3_admin_password }} login_port={{ mongodb3_mongos_port }} login_database=admin database={{ item.db }} name={{ item.name }} password={{ item.passwd }} roles={{ item.roles | join(",") }} state=present update_password=on_create
  with_items: mongodb3_users
  run_once: true


```
##### Expected Results:

when the second play is executed we must have "ok" status.
I see it's complicated du to mongo python wich not return any status on add user. But we can do a usersInfo command before and compare result (except for password)
##### Actual Results:

the second call return changed status



Discussion:
I'm experiencing this too on version 2.0.0.2-2.

i try to do a patch


Resolving patch:
diff --git a/database/misc/mongodb_user.py b/database/misc/mongodb_user.py
--- a/database/misc/mongodb_user.py
+++ b/database/misc/mongodb_user.py
@@ -148,9 +148,9 @@
 # MongoDB module specific support methods.
 #
 
-def user_find(client, user):
+def user_find(client, user, db_name):
     for mongo_user in client["admin"].system.users.find():
-        if mongo_user['user'] == user:
+        if mongo_user['user'] == user and mongo_user['db'] == db_name:
             return mongo_user
     return False
 
@@ -158,6 +158,7 @@ def user_add(module, client, db_name, user, password, roles):
     #pymono's user_add is a _create_or_update_user so we won't know if it was changed or updated
     #without reproducing a lot of the logic in database.py of pymongo
     db = client[db_name]
+
     if roles is None:
         db.add_user(user, password, False)
     else:
@@ -170,7 +171,7 @@ def user_add(module, client, db_name, user, password, roles):
             module.fail_json(msg=err_msg)
 
 def user_remove(module, client, db_name, user):
-    exists = user_find(client, user)
+    exists = user_find(client, user, db_name)
     if exists:
         db = client[db_name]
         db.remove_user(user)
@@ -192,6 +193,44 @@ def load_mongocnf():
 
     return creds
 
+
+
+def check_if_roles_changed(uinfo, roles, db_name):
+# We must be aware of users which can read the oplog on a replicaset
+# Such users must have access to the local DB, but since this DB does not store users credentials
+# and is not synchronized among replica sets, the user must be stored on the admin db
+# Therefore their structure is the following :
+# {
+#     "_id" : "admin.oplog_reader",
+#     "user" : "oplog_reader",
+#     "db" : "admin",                    # <-- admin DB
+#     "roles" : [
+#         {
+#             "role" : "read",
+#             "db" : "local"             # <-- local DB
+#         }
+#     ]
+# }
+
+    def make_sure_roles_are_a_list_of_dict(roles, db_name):
+        output = list()
+        for role in roles:
+            if isinstance(role, basestring):
+                new_role = { "role": role, "db": db_name }
+                output.append(new_role)
+            else:
+                output.append(role)
+        return output
+
+    roles_as_list_of_dict = make_sure_roles_are_a_list_of_dict(roles, db_name)
+    uinfo_roles = uinfo.get('roles', [])
+
+    if sorted(roles_as_list_of_dict) == sorted(uinfo_roles):
+        return False
+    return True
+
+
+
 # =========================================
 # Module execution.
 #
@@ -223,7 +262,7 @@ def main():
     login_host = module.params['login_host']
     login_port = module.params['login_port']
     login_database = module.params['login_database']
-    
+
     replica_set = module.params['replica_set']
     db_name = module.params['database']
     user = module.params['name']
@@ -261,14 +300,22 @@ def main():
         if password is None and update_password == 'always':
             module.fail_json(msg='password parameter required when adding a user unless update_password is set to on_create')
 
-        if update_password != 'always' and user_find(client, user):
+        uinfo = user_find(client, user, db_name)
+        if update_password != 'always' and uinfo:
             password = None
+            if not check_if_roles_changed(uinfo, roles, db_name):
+                module.exit_json(changed=False, user=user)
 
         try:
             user_add(module, client, db_name, user, password, roles)
         except OperationFailure, e:
             module.fail_json(msg='Unable to add or update user: %s' % str(e))
 
+            # Here we can  check password change if mongo provide a query for that : https://jira.mongodb.org/browse/SERVER-22848
+            #newuinfo = user_find(client, user, db_name)
+            #if uinfo['role'] == newuinfo['role'] and CheckPasswordHere:
+            #    module.exit_json(changed=False, user=user)
+
     elif state == 'absent':
         try:
             user_remove(module, client, db_name, user)


Test patch: