| 1 |
from __future__ import absolute_import, division, print_function |
| 2 |
__metaclass__ = type |
| 3 |
from ansible.module_utils.basic import missing_required_lib # pylint: disable=unused-import: |
| 4 |
from ansible.module_utils.six.moves import configparser |
| 5 |
from ansible.module_utils._text import to_native |
| 6 |
import traceback |
| 7 |
import os |
| 8 |
import ssl as ssl_lib |
| 9 |
|
| 10 |
|
| 11 |
try: |
| 12 |
from bson.timestamp import Timestamp |
| 13 |
from bson import ObjectId |
| 14 |
except ImportError: |
| 15 |
pass # TODO Should we do something here or are we covered by pymongo? |
| 16 |
|
| 17 |
MongoClient = None |
| 18 |
PYMONGO_IMP_ERR = None |
| 19 |
pymongo_found = None |
| 20 |
PyMongoVersion = None |
| 21 |
ConnectionFailure = None |
| 22 |
OperationFailure = None |
| 23 |
TYPES_NEED_TO_CONVERT = None |
| 24 |
|
| 25 |
try: |
| 26 |
from pymongo.errors import ConnectionFailure # pylint: disable=unused-import: |
| 27 |
from pymongo.errors import OperationFailure # pylint: disable=unused-import: |
| 28 |
from pymongo import version as PyMongoVersion |
| 29 |
from pymongo import MongoClient |
| 30 |
pymongo_found = True |
| 31 |
except ImportError: |
| 32 |
PYMONGO_IMP_ERR = traceback.format_exc() |
| 33 |
pymongo_found = False |
| 34 |
|
| 35 |
try: |
| 36 |
TYPES_NEED_TO_CONVERT = (Timestamp, ObjectId) |
| 37 |
except NameError: |
| 38 |
pass # sanity tests |
| 39 |
|
| 40 |
|
| 41 |
def check_compatibility(module, srv_version, driver_version): |
| 42 |
if int(driver_version[0]) >= 4: |
| 43 |
if int(srv_version[0]) < 4: |
| 44 |
if module.params['strict_compatibility']: |
| 45 |
module.fail_json(msg="This version of MongoDB is pretty old and these modules are no longer tested against this version.") |
| 46 |
else: |
| 47 |
module.warn("This version of MongoDB is pretty old and these modules are no longer tested against this version.") |
| 48 |
else: |
| 49 |
if module.params['strict_compatibility']: |
| 50 |
module.fail_json(msg="You must use pymongo 4+.") |
| 51 |
else: |
| 52 |
module.warn("You must use pymongo 4+.") |
| 53 |
|
| 54 |
|
| 55 |
def load_mongocnf(): |
| 56 |
config = configparser.RawConfigParser() |
| 57 |
mongocnf = os.path.expanduser('~/.mongodb.cnf') |
| 58 |
|
| 59 |
try: |
| 60 |
config.read_file(open(mongocnf)) |
| 61 |
except (configparser.NoOptionError, IOError): |
| 62 |
return False |
| 63 |
|
| 64 |
creds = dict( |
| 65 |
user=config.get('client', 'user'), |
| 66 |
password=config.get('client', 'pass') |
| 67 |
) |
| 68 |
|
| 69 |
return creds |
| 70 |
|
| 71 |
|
| 72 |
def index_exists(client, database, collection, index_name): |
| 73 |
""" |
| 74 |
Returns true if an index on the collection exists with the given name |
| 75 |
@client: MongoDB connection. |
| 76 |
@database: MongoDB Database. |
| 77 |
@collection: MongoDB collection. |
| 78 |
@index_name: The index name. |
| 79 |
""" |
| 80 |
exists = False |
| 81 |
indexes = client[database][collection].list_indexes() |
| 82 |
for index in indexes: |
| 83 |
if index["name"] == index_name: |
| 84 |
exists = True |
| 85 |
return exists |
| 86 |
|
| 87 |
|
| 88 |
def create_index(client, database, collection, keys, options): |
| 89 |
""" |
| 90 |
Creates an index on the given collection |
| 91 |
@client: MongoDB connection. |
| 92 |
@database: MongoDB Database - str. |
| 93 |
@collection: MongoDB collection - str. |
| 94 |
@keys: Specification of index - dict. |
| 95 |
""" |
| 96 |
client[database][collection].create_index(list(keys.items()), |
| 97 |
**options) |
| 98 |
|
| 99 |
|
| 100 |
def drop_index(client, database, collection, index_name): |
| 101 |
client[database][collection].drop_index(index_name) |
| 102 |
|
| 103 |
|
| 104 |
def member_state(client): |
| 105 |
"""Check if a replicaset exists. |
| 106 |
|
| 107 |
Args: |
| 108 |
client (cursor): Mongodb cursor on admin database. |
| 109 |
|
| 110 |
Returns: |
| 111 |
str: member state i.e. PRIMARY, SECONDARY |
| 112 |
""" |
| 113 |
state = None |
| 114 |
doc = client['admin'].command('replSetGetStatus') |
| 115 |
for member in doc["members"]: |
| 116 |
if "self" in member.keys(): |
| 117 |
state = str(member['stateStr']) |
| 118 |
return state |
| 119 |
|
| 120 |
|
| 121 |
def mongodb_common_argument_spec(ssl_options=True): |
| 122 |
""" |
| 123 |
Returns a dict containing common options shared across the MongoDB modules. |
| 124 |
""" |
| 125 |
options = dict( |
| 126 |
login_user=dict(type='str', required=False), |
| 127 |
login_password=dict(type='str', required=False, no_log=True), |
| 128 |
login_database=dict(type='str', required=False, default='admin'), |
| 129 |
login_host=dict(type='str', required=False, default='localhost'), |
| 130 |
login_port=dict(type='int', required=False, default=27017), |
| 131 |
strict_compatibility=dict(type='bool', default=True), |
| 132 |
atlas_auth=dict(type='bool', default=False), |
| 133 |
) |
| 134 |
ssl_options_dict = dict( |
| 135 |
ssl=dict(type='bool', required=False, default=False, aliases=['tls']), |
| 136 |
ssl_cert_reqs=dict(type='str', |
| 137 |
required=False, |
| 138 |
default='CERT_REQUIRED', |
| 139 |
choices=['CERT_NONE', |
| 140 |
'CERT_OPTIONAL', |
| 141 |
'CERT_REQUIRED'], |
| 142 |
aliases=['tlsAllowInvalidCertificates']), |
| 143 |
ssl_ca_certs=dict(type='str', default=None, aliases=['tlsCAFile']), |
| 144 |
ssl_crlfile=dict(type='str', default=None), |
| 145 |
ssl_certfile=dict(type='str', default=None, aliases=['tlsCertificateKeyFile']), |
| 146 |
ssl_keyfile=dict(type='str', default=None, no_log=True), |
| 147 |
ssl_pem_passphrase=dict(type='str', default=None, no_log=True, aliases=['tlsCertificateKeyFilePassword']), |
| 148 |
auth_mechanism=dict(type='str', |
| 149 |
required=False, |
| 150 |
default=None, |
| 151 |
choices=['SCRAM-SHA-256', |
| 152 |
'SCRAM-SHA-1', |
| 153 |
'MONGODB-X509', |
| 154 |
'GSSAPI', |
| 155 |
'PLAIN']), |
| 156 |
connection_options=dict(type='list', |
| 157 |
elements='raw', |
| 158 |
default=None) |
| 159 |
) |
| 160 |
if ssl_options: |
| 161 |
options.update(ssl_options_dict) |
| 162 |
return options |
| 163 |
|
| 164 |
|
| 165 |
def rename_ssl_option_for_pymongo4(connection_options): |
| 166 |
""" |
| 167 |
This function renames the old ssl parameter, and sorts the data out, |
| 168 |
when the driver use is >= PyMongo 4 |
| 169 |
""" |
| 170 |
if int(PyMongoVersion[0]) >= 4: |
| 171 |
if connection_options.get('ssl_cert_reqs', None) in ('CERT_NONE', ssl_lib.CERT_NONE): |
| 172 |
connection_options['tlsAllowInvalidCertificates'] = True |
| 173 |
elif connection_options.get('ssl_cert_reqs', None) in ('CERT_REQUIRED', ssl_lib.CERT_REQUIRED): |
| 174 |
connection_options['tlsAllowInvalidCertificates'] = False |
| 175 |
connection_options.pop('ssl_cert_reqs', None) |
| 176 |
if connection_options.get('ssl_ca_certs', None) is not None: |
| 177 |
connection_options['tlsCAFile'] = connection_options['ssl_ca_certs'] |
| 178 |
connection_options.pop('ssl_ca_certs', None) |
| 179 |
connection_options.pop('ssl_crlfile', None) |
| 180 |
if connection_options.get('ssl_certfile', None) is not None: |
| 181 |
connection_options['tlsCertificateKeyFile'] = connection_options['ssl_certfile'] |
| 182 |
elif connection_options.get('ssl_keyfile', None) is not None: |
| 183 |
connection_options['tlsCertificateKeyFile'] = connection_options['ssl_keyfile'] |
| 184 |
connection_options.pop('ssl_certfile', None) |
| 185 |
connection_options.pop('ssl_keyfile', None) |
| 186 |
if connection_options.get('ssl_pem_passphrase', None) is not None: |
| 187 |
connection_options['tlsCertificateKeyFilePassword'] = connection_options['ssl_pem_passphrase'] |
| 188 |
connection_options.pop('ssl_pem_passphrase', None) |
| 189 |
return connection_options |
| 190 |
|
| 191 |
|
| 192 |
def add_option_if_not_none(param_name, module, connection_params): |
| 193 |
''' |
| 194 |
@param_name - The parameter name to check |
| 195 |
@module - The ansible module object |
| 196 |
@connection_params - Dict containing the connection params |
| 197 |
''' |
| 198 |
if module.params[param_name] is not None: |
| 199 |
connection_params[param_name] = module.params[param_name] |
| 200 |
return connection_params |
| 201 |
|
| 202 |
|
| 203 |
def ssl_connection_options(connection_params, module): |
| 204 |
connection_params['ssl'] = True |
| 205 |
if module.params['ssl_cert_reqs'] is not None: |
| 206 |
connection_params['ssl_cert_reqs'] = getattr(ssl_lib, module.params['ssl_cert_reqs']) |
| 207 |
connection_params = add_option_if_not_none('ssl_ca_certs', module, connection_params) |
| 208 |
connection_params = add_option_if_not_none('ssl_crlfile', module, connection_params) |
| 209 |
connection_params = add_option_if_not_none('ssl_certfile', module, connection_params) |
| 210 |
connection_params = add_option_if_not_none('ssl_keyfile', module, connection_params) |
| 211 |
connection_params = add_option_if_not_none('ssl_pem_passphrase', module, connection_params) |
| 212 |
if module.params['auth_mechanism'] is not None: |
| 213 |
connection_params['authMechanism'] = module.params['auth_mechanism'] |
| 214 |
if module.params['connection_options'] is not None: |
| 215 |
for item in module.params['connection_options']: |
| 216 |
if isinstance(item, dict): |
| 217 |
for key, value in item.items(): |
| 218 |
connection_params[key] = value |
| 219 |
elif isinstance(item, str) and "=" in item: |
| 220 |
connection_params[item.split('=')[0]] = item.split('=')[1] |
| 221 |
else: |
| 222 |
raise ValueError("Invalid value supplied in connection_options: {0} .".format(str(item))) |
| 223 |
return connection_params |
| 224 |
|
| 225 |
|
| 226 |
def check_srv_version(module, client): |
| 227 |
srv_version = None |
| 228 |
try: |
| 229 |
srv_version = client.server_info()['version'] |
| 230 |
except Exception as excep: |
| 231 |
module.fail_json(msg='Unable to get MongoDB server version: %s' % to_native(excep)) |
| 232 |
return srv_version |
| 233 |
|
| 234 |
|
| 235 |
def check_driver_compatibility(module, client, srv_version): |
| 236 |
try: |
| 237 |
# Get driver version:: |
| 238 |
driver_version = PyMongoVersion |
| 239 |
# Check driver and server version compatibility: |
| 240 |
check_compatibility(module, srv_version, driver_version) |
| 241 |
except Exception as excep: |
| 242 |
module.fail_json(msg='Unable to check driver compatibility: %s' % to_native(excep)) |
| 243 |
|
| 244 |
|
| 245 |
def get_mongodb_client(module, login_user=None, login_password=None, login_database=None, directConnection=False): |
| 246 |
""" |
| 247 |
Build the connection params dict and returns a MongoDB Client object |
| 248 |
""" |
| 249 |
connection_params = { |
| 250 |
'host': module.params['login_host'], |
| 251 |
'port': module.params['login_port'], |
| 252 |
} |
| 253 |
|
| 254 |
if directConnection: |
| 255 |
connection_params['directConnection'] = True |
| 256 |
if module.params['ssl']: |
| 257 |
connection_params = ssl_connection_options(connection_params, module) |
| 258 |
connection_params = rename_ssl_option_for_pymongo4(connection_params) |
| 259 |
# param exists only in some modules |
| 260 |
if 'replica_set' in module.params and 'reconfigure' not in module.params: |
| 261 |
connection_params["replicaset"] = module.params['replica_set'] |
| 262 |
elif 'replica_set' in module.params and 'reconfigure' in module.params \ |
| 263 |
and module.params['reconfigure']: |
| 264 |
connection_params["replicaset"] = module.params['replica_set'] |
| 265 |
if login_user: |
| 266 |
connection_params['username'] = login_user |
| 267 |
connection_params['password'] = login_password |
| 268 |
connection_params['authSource'] = login_database |
| 269 |
client = MongoClient(**connection_params) |
| 270 |
return client |
| 271 |
|
| 272 |
|
| 273 |
def is_auth_enabled(module): |
| 274 |
""" |
| 275 |
Returns True if auth is enabled on the mongo instance |
| 276 |
For PyMongo 4+ we have to connect directly to the instance |
| 277 |
rather than the replicaset |
| 278 |
""" |
| 279 |
auth_is_enabled = None |
| 280 |
connection_params = {} |
| 281 |
connection_params['host'] = module.params['login_host'] |
| 282 |
connection_params['port'] = module.params['login_port'] |
| 283 |
connection_params['directConnection'] = True # Need to do this for 3.12.* as well |
| 284 |
if int(PyMongoVersion[0]) >= 4: # we need to connect directly to the instance |
| 285 |
connection_params['directConnection'] = True |
| 286 |
else: |
| 287 |
if 'replica_set' in module.params and module.params['replica_set'] is not None: |
| 288 |
connection_params['replicaset'] = module.params['replica_set'] |
| 289 |
if module.params['ssl']: |
| 290 |
connection_params = ssl_connection_options(connection_params, module) |
| 291 |
connection_params = rename_ssl_option_for_pymongo4(connection_params) |
| 292 |
try: |
| 293 |
myclient = MongoClient(**connection_params) |
| 294 |
hello_response = myclient.admin.command('hello') |
| 295 |
if 'arbiterOnly' in hello_response and hello_response['arbiterOnly']: |
| 296 |
auth_is_enabled = False # Arbiters cannot login with a user |
| 297 |
else: |
| 298 |
myclient['admin'].command('listDatabases', 1.0) |
| 299 |
auth_is_enabled = False |
| 300 |
except Exception as excep: |
| 301 |
if hasattr(excep, 'code') and excep.code in [13]: |
| 302 |
auth_is_enabled = True |
| 303 |
if auth_is_enabled is None: # if this is still none we have a problem |
| 304 |
module.fail_json(msg='Unable to determine if auth is enabled: {0}'.format(traceback.format_exc())) |
| 305 |
finally: |
| 306 |
myclient.close() |
| 307 |
return auth_is_enabled |
| 308 |
|
| 309 |
|
| 310 |
def mongo_auth(module, client, directConnection=False): |
| 311 |
""" |
| 312 |
TODO: This function was extracted from code from the mongodb_replicaset module. |
| 313 |
We should refactor other modules to use this where appropriate. - DONE? |
| 314 |
@module - The calling Ansible module |
| 315 |
@client - The MongoDB connection object |
| 316 |
""" |
| 317 |
login_user = module.params['login_user'] |
| 318 |
login_password = module.params['login_password'] |
| 319 |
login_database = module.params['login_database'] |
| 320 |
|
| 321 |
atlas_auth = module.params['atlas_auth'] |
| 322 |
|
| 323 |
fail_msg = None # Our test code had issues with multiple exit points with fail_json |
| 324 |
|
| 325 |
crypt_flag = 'ssl' |
| 326 |
if 'tls' in module.params: |
| 327 |
crypt_flag = 'tls' |
| 328 |
|
| 329 |
if not atlas_auth: |
| 330 |
|
| 331 |
if login_user is None and login_password is None: |
| 332 |
mongocnf_creds = load_mongocnf() |
| 333 |
if mongocnf_creds is not False: |
| 334 |
login_user = mongocnf_creds['user'] |
| 335 |
login_password = mongocnf_creds['password'] |
| 336 |
elif not all([login_user, login_password]) and module.params[crypt_flag] is False: |
| 337 |
fail_msg = "When supplying login arguments, both 'login_user' and 'login_password' must be provided" |
| 338 |
|
| 339 |
if 'create_for_localhost_exception' not in module.params and fail_msg is None: |
| 340 |
try: |
| 341 |
if is_auth_enabled(module): |
| 342 |
if login_user is not None and login_password is not None: |
| 343 |
client = get_mongodb_client(module, login_user, login_password, login_database, directConnection=directConnection) |
| 344 |
else: |
| 345 |
fail_msg = 'No credentials to authenticate' |
| 346 |
except Exception as excep: |
| 347 |
fail_msg = 'unable to connect to database: %s' % to_native(excep) |
| 348 |
# Get server version: |
| 349 |
if fail_msg is None: |
| 350 |
srv_version = check_srv_version(module, client) |
| 351 |
check_driver_compatibility(module, client, srv_version) |
| 352 |
elif fail_msg is None: # this is the mongodb_user module |
| 353 |
if login_user is not None and login_password is not None: |
| 354 |
client = get_mongodb_client(module, login_user, login_password, login_database, directConnection=directConnection) |
| 355 |
# Get server version: |
| 356 |
srv_version = check_srv_version(module, client) |
| 357 |
check_driver_compatibility(module, client, srv_version) |
| 358 |
elif module.params['strict_compatibility'] is False: |
| 359 |
if module.params['database'] not in ["admin", "$external"]: |
| 360 |
fail_msg = 'The localhost login exception only allows the first admin account to be created' |
| 361 |
# else: this has to be the first admin user added |
| 362 |
if fail_msg: |
| 363 |
module.fail_json(msg=fail_msg) |
| 364 |
else: # Atlas auth path |
| 365 |
if 'create_for_localhost_exception' not in module.params and fail_msg is None: |
| 366 |
try: |
| 367 |
if login_user is not None and login_password is not None: |
| 368 |
# pymongo >= 4. There's no authenticate method in pymongo 4.0. Recreate the connection object |
| 369 |
client = get_mongodb_client(module, login_user, login_password, login_database) |
| 370 |
else: |
| 371 |
fail_msg = 'No credentials to authenticate' |
| 372 |
except Exception as excep: |
| 373 |
fail_msg = 'unable to connect to database: %s' % to_native(excep) |
| 374 |
elif fail_msg is None: # this is the mongodb_user module |
| 375 |
if login_user is not None and login_password is not None: |
| 376 |
client = get_mongodb_client(module, login_user, login_password, login_database, directConnection=False) |
| 377 |
# Get server version: |
| 378 |
srv_version = check_srv_version(module, client) |
| 379 |
check_driver_compatibility(module, client, srv_version) |
| 380 |
elif module.params['strict_compatibility'] is False: |
| 381 |
if module.params['database'] not in ["admin", "$external"]: |
| 382 |
fail_msg = 'The localhost login exception only allows the first admin account to be created' |
| 383 |
# else: this has to be the first admin user added |
| 384 |
if fail_msg: |
| 385 |
module.fail_json(msg=fail_msg) |
| 386 |
return client |
| 387 |
|
| 388 |
|
| 389 |
def member_dicts_different(conf, member_config): |
| 390 |
''' |
| 391 |
Returns if there is a difference in the replicaset configuration that we care about |
| 392 |
@con - The current MongoDB Replicaset configure document |
| 393 |
@member_config - The member dict config provided by the module. List of dicts |
| 394 |
''' |
| 395 |
current_member_config = conf['members'] |
| 396 |
member_config_defaults = { |
| 397 |
"arbiterOnly": False, |
| 398 |
"buildIndexes": True, |
| 399 |
"hidden": False, |
| 400 |
"priority": {"nonarbiter": 1.0, "arbiter": 0}, |
| 401 |
"tags": {}, |
| 402 |
"horizons": {}, |
| 403 |
"secondaryDelaySecs": 0, |
| 404 |
"votes": 1 |
| 405 |
} |
| 406 |
different = False |
| 407 |
msg = "None" |
| 408 |
current_member_hosts = [] |
| 409 |
for member in current_member_config: |
| 410 |
current_member_hosts.append(member['host']) |
| 411 |
member_config_hosts = [] |
| 412 |
for member in member_config: |
| 413 |
if ':' not in member['host']: # no port supplied |
| 414 |
member_config_hosts.append(member['host'] + ":27017") |
| 415 |
else: |
| 416 |
member_config_hosts.append(member['host']) |
| 417 |
if sorted(current_member_hosts) != sorted(member_config_hosts): # compare if members are the same |
| 418 |
different = True |
| 419 |
msg = "hosts different" |
| 420 |
else: # Compare dict key to see if votes, tags etc have changed. We also default value if key is not specified |
| 421 |
for host in current_member_hosts: |
| 422 |
member_index = next((index for (index, d) in enumerate(current_member_config) if d["host"] == host), None) |
| 423 |
new_member_index = next((index for (index, d) in enumerate(member_config) if d["host"] == host), None) |
| 424 |
for config_item in member_config_defaults: |
| 425 |
if config_item != "priority": |
| 426 |
if current_member_config[member_index].get(config_item, member_config_defaults[config_item]) != \ |
| 427 |
member_config[new_member_index].get(config_item, member_config_defaults[config_item]): |
| 428 |
different = True |
| 429 |
msg = "var different {0} {1} {2}".format(config_item, |
| 430 |
current_member_config[member_index].get(config_item, member_config_defaults[config_item]), |
| 431 |
member_config[new_member_index].get(config_item, member_config_defaults[config_item])) |
| 432 |
break |
| 433 |
else: # priority a special case |
| 434 |
role = "nonarbiter" |
| 435 |
if current_member_config[member_index]["arbiterOnly"]: |
| 436 |
role = "arbiter" |
| 437 |
if current_member_config[member_index][config_item] != \ |
| 438 |
member_config[new_member_index].get(config_item, member_config_defaults[config_item][role]): |
| 439 |
different = True |
| 440 |
msg = "var different {0}".format(config_item) |
| 441 |
break |
| 442 |
else: # for case when the member is not an arbiter |
| 443 |
if current_member_config[member_index]["priority"] != \ |
| 444 |
member_config[new_member_index].get(config_item, 1.0): |
| 445 |
different = True |
| 446 |
msg = "var different {0}".format(config_item) |
| 447 |
break |
| 448 |
return different # , msg |
| 449 |
|
| 450 |
|
| 451 |
def lists_are_different(list1, list2): |
| 452 |
diff = False |
| 453 |
if sorted(list1) != sorted(list2): |
| 454 |
diff = True |
| 455 |
return diff |
| 456 |
|
| 457 |
|
| 458 |
# Taken from https://github.com/ansible-collections/community.postgresql/blob/main/plugins/module_utils/postgres.py#L420 |
| 459 |
def convert_to_supported(val): |
| 460 |
"""Convert unsupported type to appropriate. |
| 461 |
Args: |
| 462 |
val (any) -- Any value fetched from database. |
| 463 |
Returns value of appropriate type. |
| 464 |
""" |
| 465 |
if isinstance(val, Timestamp): |
| 466 |
return str(val) |
| 467 |
elif isinstance(val, ObjectId): |
| 468 |
return str(val) |
| 469 |
|
| 470 |
return val # By default returns the same value |
| 471 |
|
| 472 |
|
| 473 |
def convert_bson_values_recur(mydict): |
| 474 |
""" |
| 475 |
Converts values that Ansible doesn't like |
| 476 |
# https://github.com/ansible-collections/community.mongodb/issues/462 |
| 477 |
""" |
| 478 |
if isinstance(mydict, dict): |
| 479 |
for key, value in mydict.items(): |
| 480 |
if isinstance(value, dict): |
| 481 |
mydict[key] = convert_bson_values_recur(value) |
| 482 |
else: |
| 483 |
if isinstance(value, TYPES_NEED_TO_CONVERT): |
| 484 |
mydict[key] = convert_to_supported(value) |
| 485 |
else: |
| 486 |
mydict[key] = value |
| 487 |
return mydict |