| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# (c) 2012, Elliott Foster <[email protected]> |
| 4 |
# Sponsored by Four Kitchens http://fourkitchens.com. |
| 5 |
# (c) 2014, Epic Games, Inc. |
| 6 |
# |
| 7 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = ''' |
| 14 |
--- |
| 15 |
module: mongodb_user |
| 16 |
short_description: Adds or removes a user from a MongoDB database |
| 17 |
description: |
| 18 |
- Adds or removes a user from a MongoDB database. |
| 19 |
version_added: "1.0.0" |
| 20 |
|
| 21 |
extends_documentation_fragment: |
| 22 |
- community.mongodb.login_options |
| 23 |
- community.mongodb.ssl_options |
| 24 |
|
| 25 |
options: |
| 26 |
replica_set: |
| 27 |
description: |
| 28 |
- Replica set to connect to (automatically connects to primary for writes). |
| 29 |
- Leave empty if you need the localhost exception, e.g. to create the initial user |
| 30 |
type: str |
| 31 |
database: |
| 32 |
description: |
| 33 |
- The name of the database to add/remove the user from. |
| 34 |
required: true |
| 35 |
type: str |
| 36 |
aliases: [db] |
| 37 |
name: |
| 38 |
description: |
| 39 |
- The name of the user to add or remove. |
| 40 |
required: true |
| 41 |
aliases: [user] |
| 42 |
type: str |
| 43 |
password: |
| 44 |
description: |
| 45 |
- The password to use for the user. |
| 46 |
type: str |
| 47 |
aliases: [pass] |
| 48 |
roles: |
| 49 |
type: list |
| 50 |
elements: raw |
| 51 |
description: |
| 52 |
- > |
| 53 |
The database user roles valid values could either be one or more of the following strings: |
| 54 |
'read', 'readWrite', 'dbAdmin', 'userAdmin', 'clusterAdmin', 'readAnyDatabase', 'readWriteAnyDatabase', 'userAdminAnyDatabase', |
| 55 |
'dbAdminAnyDatabase' |
| 56 |
- "Or the following dictionary '{ db: DATABASE_NAME, role: ROLE_NAME }'." |
| 57 |
- "This param requires pymongo 2.5+. If it is a string, mongodb 2.4+ is also required. If it is a dictionary, mongo 2.6+ is required." |
| 58 |
state: |
| 59 |
description: |
| 60 |
- The database user state. |
| 61 |
default: present |
| 62 |
choices: [absent, present] |
| 63 |
type: str |
| 64 |
update_password: |
| 65 |
default: always |
| 66 |
choices: [always, on_create] |
| 67 |
description: |
| 68 |
- C(always) will always update passwords and cause the module to return changed. |
| 69 |
- C(on_create) will only set the password for newly created users. |
| 70 |
- This must be C(always) to use the localhost exception when adding the first admin user. |
| 71 |
- This option is effectively ignored when using x.509 certs. It is defaulted to 'on_create' to maintain a \ |
| 72 |
a specific module behaviour when the login_database is '$external'. |
| 73 |
type: str |
| 74 |
create_for_localhost_exception: |
| 75 |
type: path |
| 76 |
description: |
| 77 |
- This is parmeter is only useful for handling special treatment around the localhost exception. |
| 78 |
- If C(login_user) is defined, then the localhost exception is not active and this parameter has no effect. |
| 79 |
- If this file is NOT present (and C(login_user) is not defined), then touch this file after successfully adding the user. |
| 80 |
- If this file is present (and C(login_user) is not defined), then skip this task. |
| 81 |
|
| 82 |
notes: |
| 83 |
- Requires the pymongo Python package on the remote host, version 4+. This |
| 84 |
can be installed using pip or the OS package manager. Newer mongo server versions require newer |
| 85 |
pymongo versions. @see https://www.mongodb.com/docs/languages/python/pymongo-driver/current/compatibility/ |
| 86 |
requirements: |
| 87 |
- "pymongo" |
| 88 |
author: |
| 89 |
- "Elliott Foster (@elliotttf)" |
| 90 |
- "Julien Thebault (@Lujeni)" |
| 91 |
''' |
| 92 |
|
| 93 |
EXAMPLES = ''' |
| 94 |
- name: Create 'burgers' database user with name 'bob' and password '12345'. |
| 95 |
community.mongodb.mongodb_user: |
| 96 |
database: burgers |
| 97 |
name: bob |
| 98 |
password: 12345 |
| 99 |
state: present |
| 100 |
|
| 101 |
- name: Create a database user via SSL (MongoDB must be compiled with the SSL option and configured properly) |
| 102 |
community.mongodb.mongodb_user: |
| 103 |
database: burgers |
| 104 |
name: bob |
| 105 |
password: 12345 |
| 106 |
state: present |
| 107 |
ssl: True |
| 108 |
|
| 109 |
- name: Delete 'burgers' database user with name 'bob'. |
| 110 |
community.mongodb.mongodb_user: |
| 111 |
database: burgers |
| 112 |
name: bob |
| 113 |
state: absent |
| 114 |
|
| 115 |
- name: Define more users with various specific roles (if not defined, no roles is assigned, and the user will be added via pre mongo 2.2 style) |
| 116 |
community.mongodb.mongodb_user: |
| 117 |
database: burgers |
| 118 |
name: ben |
| 119 |
password: 12345 |
| 120 |
roles: read |
| 121 |
state: present |
| 122 |
|
| 123 |
- name: Define roles |
| 124 |
community.mongodb.mongodb_user: |
| 125 |
database: burgers |
| 126 |
name: jim |
| 127 |
password: 12345 |
| 128 |
roles: readWrite,dbAdmin,userAdmin |
| 129 |
state: present |
| 130 |
|
| 131 |
- name: Define roles |
| 132 |
community.mongodb.mongodb_user: |
| 133 |
database: burgers |
| 134 |
name: joe |
| 135 |
password: 12345 |
| 136 |
roles: readWriteAnyDatabase |
| 137 |
state: present |
| 138 |
|
| 139 |
- name: Add a user to database in a replica set, the primary server is automatically discovered and written to |
| 140 |
community.mongodb.mongodb_user: |
| 141 |
database: burgers |
| 142 |
name: bob |
| 143 |
replica_set: belcher |
| 144 |
password: 12345 |
| 145 |
roles: readWriteAnyDatabase |
| 146 |
state: present |
| 147 |
|
| 148 |
# add a user 'oplog_reader' with read only access to the 'local' database on the replica_set 'belcher'. This is useful for oplog access (MONGO_OPLOG_URL). |
| 149 |
# please notice the credentials must be added to the 'admin' database because the 'local' database is not synchronized and can't receive user credentials |
| 150 |
# To login with such user, the connection string should be MONGO_OPLOG_URL="mongodb://oplog_reader:oplog_reader_password@server1,server2/local?authSource=admin" |
| 151 |
# This syntax requires mongodb 2.6+ and pymongo 2.5+ |
| 152 |
- name: Roles as a dictionary |
| 153 |
community.mongodb.mongodb_user: |
| 154 |
login_user: root |
| 155 |
login_password: root_password |
| 156 |
database: admin |
| 157 |
user: oplog_reader |
| 158 |
password: oplog_reader_password |
| 159 |
state: present |
| 160 |
replica_set: belcher |
| 161 |
roles: |
| 162 |
- db: local |
| 163 |
role: read |
| 164 |
|
| 165 |
- name: Adding a user with X.509 Member Authentication |
| 166 |
community.mongodb.mongodb_user: |
| 167 |
login_host: "mongodb-host.test" |
| 168 |
login_port: 27001 |
| 169 |
login_database: "$external" |
| 170 |
database: "admin" |
| 171 |
name: "admin" |
| 172 |
password: "test" |
| 173 |
roles: |
| 174 |
- dbAdminAnyDatabase |
| 175 |
ssl: true |
| 176 |
ssl_ca_certs: "/tmp/ca.crt" |
| 177 |
ssl_certfile: "/tmp/tls.key" #cert and key in one file |
| 178 |
state: present |
| 179 |
auth_mechanism: "MONGODB-X509" |
| 180 |
connection_options: |
| 181 |
- "tlsAllowInvalidHostnames=true" |
| 182 |
''' |
| 183 |
|
| 184 |
RETURN = ''' |
| 185 |
user: |
| 186 |
description: The name of the user to add or remove. |
| 187 |
returned: success |
| 188 |
type: str |
| 189 |
''' |
| 190 |
|
| 191 |
import os |
| 192 |
import traceback |
| 193 |
|
| 194 |
|
| 195 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 196 |
from ansible.module_utils.six import binary_type, text_type # pylint: disable=ansible-bad-import-from |
| 197 |
from ansible.module_utils._text import to_native, to_bytes |
| 198 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 199 |
missing_required_lib, |
| 200 |
mongodb_common_argument_spec, |
| 201 |
mongo_auth, |
| 202 |
PYMONGO_IMP_ERR, |
| 203 |
pymongo_found, |
| 204 |
get_mongodb_client, |
| 205 |
) |
| 206 |
|
| 207 |
|
| 208 |
def user_find(client, user, db_name): |
| 209 |
"""Check if the user exists. |
| 210 |
|
| 211 |
Args: |
| 212 |
client (cursor): Mongodb cursor on admin database. |
| 213 |
user (str): User to check. |
| 214 |
db_name (str): User's database. |
| 215 |
|
| 216 |
Returns: |
| 217 |
dict: when user exists, False otherwise. |
| 218 |
""" |
| 219 |
try: |
| 220 |
for mongo_user in client[db_name].command('usersInfo')['users']: |
| 221 |
if mongo_user['user'] == user: |
| 222 |
# NOTE: there is no 'db' field in mongo 2.4. |
| 223 |
if 'db' not in mongo_user: |
| 224 |
return mongo_user |
| 225 |
# Workaround to make the condition works with AWS DocumentDB, |
| 226 |
# since all users are in the admin database. |
| 227 |
if mongo_user["db"] in [db_name, "admin"]: |
| 228 |
return mongo_user |
| 229 |
except Exception as excep: |
| 230 |
if hasattr(excep, 'code') and excep.code == 11: # 11=UserNotFound |
| 231 |
pass # Allow return False |
| 232 |
else: |
| 233 |
raise |
| 234 |
return False |
| 235 |
|
| 236 |
|
| 237 |
def user_add(module, client, db_name, user, password, roles): |
| 238 |
# pymongo's user_add is a _create_or_update_user so we won't know if it was changed or updated |
| 239 |
# without reproducing a lot of the logic in database.py of pymongo |
| 240 |
db = client[db_name] |
| 241 |
|
| 242 |
try: |
| 243 |
exists = user_find(client, user, db_name) |
| 244 |
except Exception as excep: |
| 245 |
# We get this exception: "not authorized on admin to execute command" |
| 246 |
# when auth is enabled on a new instance. The loalhost exception should |
| 247 |
# allow us to create the first user. If the localhost exception does not apply, |
| 248 |
# then user creation will also fail with unauthorized. So, ignore Unauthorized here. |
| 249 |
if hasattr(excep, 'code') and excep.code == 13: # 13=Unauthorized |
| 250 |
exists = False |
| 251 |
else: |
| 252 |
raise |
| 253 |
|
| 254 |
if exists: |
| 255 |
user_add_db_command = 'updateUser' |
| 256 |
else: |
| 257 |
user_add_db_command = 'createUser' |
| 258 |
|
| 259 |
user_dict = {} |
| 260 |
|
| 261 |
if password is not None: |
| 262 |
user_dict["pwd"] = password |
| 263 |
if roles is not None: |
| 264 |
user_dict["roles"] = roles |
| 265 |
|
| 266 |
db.command(user_add_db_command, user, **user_dict) |
| 267 |
|
| 268 |
|
| 269 |
def user_remove(module, client, db_name, user): |
| 270 |
exists = user_find(client, user, db_name) |
| 271 |
if exists: |
| 272 |
if module.check_mode: |
| 273 |
module.exit_json(changed=True, user=user) |
| 274 |
db = client[db_name] |
| 275 |
db.command("dropUser", user) |
| 276 |
else: |
| 277 |
module.exit_json(changed=False, user=user) |
| 278 |
|
| 279 |
|
| 280 |
def check_if_roles_changed(uinfo, roles, db_name): |
| 281 |
# We must be aware of users which can read the oplog on a replicaset |
| 282 |
# Such users must have access to the local DB, but since this DB does not store users credentials |
| 283 |
# and is not synchronized among replica sets, the user must be stored on the admin db |
| 284 |
# Therefore their structure is the following : |
| 285 |
# { |
| 286 |
# "_id" : "admin.oplog_reader", |
| 287 |
# "user" : "oplog_reader", |
| 288 |
# "db" : "admin", # <-- admin DB |
| 289 |
# "roles" : [ |
| 290 |
# { |
| 291 |
# "role" : "read", |
| 292 |
# "db" : "local" # <-- local DB |
| 293 |
# } |
| 294 |
# ] |
| 295 |
# } |
| 296 |
|
| 297 |
def make_sure_roles_are_a_list_of_dict(roles, db_name): |
| 298 |
output = list() |
| 299 |
for role in roles: |
| 300 |
if isinstance(role, (binary_type, text_type)): |
| 301 |
new_role = {"role": role, "db": db_name} |
| 302 |
output.append(new_role) |
| 303 |
else: |
| 304 |
output.append(role) |
| 305 |
return output |
| 306 |
|
| 307 |
roles_as_list_of_dict = make_sure_roles_are_a_list_of_dict(roles, db_name) |
| 308 |
uinfo_roles = uinfo.get('roles', []) |
| 309 |
|
| 310 |
if sorted(roles_as_list_of_dict, key=lambda roles: sorted(roles.items())) == sorted(uinfo_roles, key=lambda roles: sorted(roles.items())): |
| 311 |
return False |
| 312 |
return True |
| 313 |
|
| 314 |
|
| 315 |
# ========================================= |
| 316 |
# Module execution. |
| 317 |
# |
| 318 |
|
| 319 |
def main(): |
| 320 |
argument_spec = mongodb_common_argument_spec() |
| 321 |
argument_spec.update( |
| 322 |
database=dict(required=True, aliases=['db']), |
| 323 |
name=dict(required=True, aliases=['user']), |
| 324 |
password=dict(aliases=['pass'], no_log=True), |
| 325 |
replica_set=dict(default=None), |
| 326 |
roles=dict(default=None, type='list', elements='raw'), |
| 327 |
state=dict(default='present', choices=['absent', 'present']), |
| 328 |
update_password=dict(default="always", choices=["always", "on_create"], no_log=False), |
| 329 |
create_for_localhost_exception=dict(default=None, type='path'), |
| 330 |
) |
| 331 |
module = AnsibleModule( |
| 332 |
argument_spec=argument_spec, |
| 333 |
supports_check_mode=True, |
| 334 |
) |
| 335 |
login_user = module.params['login_user'] |
| 336 |
|
| 337 |
# Certs don't have a password but we want this module behaviour |
| 338 |
if module.params['login_database'] == '$external': |
| 339 |
module.params['update_password'] = 'on_create' |
| 340 |
|
| 341 |
if not pymongo_found: |
| 342 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 343 |
exception=PYMONGO_IMP_ERR) |
| 344 |
|
| 345 |
create_for_localhost_exception = module.params['create_for_localhost_exception'] |
| 346 |
b_create_for_localhost_exception = ( |
| 347 |
to_bytes(create_for_localhost_exception, errors='surrogate_or_strict') |
| 348 |
if create_for_localhost_exception is not None else None |
| 349 |
) |
| 350 |
|
| 351 |
db_name = module.params['database'] |
| 352 |
user = module.params['name'] |
| 353 |
password = module.params['password'] |
| 354 |
roles = module.params['roles'] or [] |
| 355 |
state = module.params['state'] |
| 356 |
update_password = module.params['update_password'] |
| 357 |
|
| 358 |
try: |
| 359 |
directConnection = False |
| 360 |
if module.params['replica_set'] is None: |
| 361 |
directConnection = True |
| 362 |
client = get_mongodb_client(module, directConnection=directConnection) |
| 363 |
client = mongo_auth(module, client, directConnection=directConnection) |
| 364 |
except Exception as e: |
| 365 |
module.fail_json(msg='Unable to connect to database: %s' % to_native(e)) |
| 366 |
|
| 367 |
if state == 'present': |
| 368 |
if password is None and update_password == 'always': |
| 369 |
module.fail_json(msg='password parameter required when adding a user unless update_password is set to on_create') |
| 370 |
|
| 371 |
if login_user is None and create_for_localhost_exception is not None: |
| 372 |
if os.path.exists(b_create_for_localhost_exception): |
| 373 |
try: |
| 374 |
client.close() |
| 375 |
except Exception: |
| 376 |
pass |
| 377 |
module.exit_json(changed=False, user=user, skipped=True, msg="The path in create_for_localhost_exception exists.") |
| 378 |
|
| 379 |
try: |
| 380 |
if update_password != 'always': |
| 381 |
uinfo = user_find(client, user, db_name) |
| 382 |
if uinfo: |
| 383 |
password = None |
| 384 |
if not check_if_roles_changed(uinfo, roles, db_name): |
| 385 |
module.exit_json(changed=False, user=user) |
| 386 |
|
| 387 |
if module.check_mode: |
| 388 |
module.exit_json(changed=True, user=user) |
| 389 |
user_add(module, client, db_name, user, password, roles) |
| 390 |
except Exception as e: |
| 391 |
module.fail_json(msg='Unable to add or update user: %s' % to_native(e), exception=traceback.format_exc()) |
| 392 |
finally: |
| 393 |
try: |
| 394 |
client.close() |
| 395 |
except Exception: |
| 396 |
pass |
| 397 |
# Here we can check password change if mongo provide a query for that : https://jira.mongodb.org/browse/SERVER-22848 |
| 398 |
# newuinfo = user_find(client, user, db_name) |
| 399 |
# if uinfo['role'] == newuinfo['role'] and CheckPasswordHere: |
| 400 |
# module.exit_json(changed=False, user=user) |
| 401 |
|
| 402 |
if login_user is None and create_for_localhost_exception is not None: |
| 403 |
# localhost exception applied. |
| 404 |
try: |
| 405 |
# touch the file |
| 406 |
open(b_create_for_localhost_exception, 'wb').close() |
| 407 |
except Exception as e: |
| 408 |
module.fail_json( |
| 409 |
changed=True, |
| 410 |
msg='Added user but unable to touch create_for_localhost_exception file %s: %s' % (create_for_localhost_exception, to_native(e)), |
| 411 |
exception=traceback.format_exc() |
| 412 |
) |
| 413 |
|
| 414 |
elif state == 'absent': |
| 415 |
try: |
| 416 |
user_remove(module, client, db_name, user) |
| 417 |
except Exception as e: |
| 418 |
module.fail_json(msg='Unable to remove user: %s' % to_native(e), exception=traceback.format_exc()) |
| 419 |
finally: |
| 420 |
try: |
| 421 |
client.close() |
| 422 |
except Exception: |
| 423 |
pass |
| 424 |
module.exit_json(changed=True, user=user) |
| 425 |
|
| 426 |
|
| 427 |
if __name__ == '__main__': |
| 428 |
main() |