| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright: (c) 2018, Rhys Campbell <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
__metaclass__ = type |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = r''' |
| 11 |
--- |
| 12 |
module: mongodb_replicaset |
| 13 |
short_description: Initialises a MongoDB replicaset. |
| 14 |
description: |
| 15 |
- Initialises a MongoDB replicaset in a new deployment. |
| 16 |
- Validates the replicaset name for existing deployments. |
| 17 |
- Advanced replicaset member (re)configuration possible (see examples). |
| 18 |
- Initialize the replicaset before adding users as per \ |
| 19 |
[best practice](https://www.mongodb.com/docs/manual/tutorial/deploy-replica-set-with-keyfile-access-control/). |
| 20 |
author: Rhys Campbell (@rhysmeister) |
| 21 |
version_added: "1.0.0" |
| 22 |
|
| 23 |
extends_documentation_fragment: |
| 24 |
- community.mongodb.login_options |
| 25 |
- community.mongodb.ssl_options |
| 26 |
|
| 27 |
options: |
| 28 |
replica_set: |
| 29 |
description: |
| 30 |
- Replicaset name. |
| 31 |
type: str |
| 32 |
default: rs0 |
| 33 |
members: |
| 34 |
description: |
| 35 |
- Yaml list consisting of the replicaset members. |
| 36 |
- Csv string will also be accepted i.e. mongodb1:27017,mongodb2:27017,mongodb3:27017. |
| 37 |
- A dictionary can also be used to specify advanced replicaset member options. |
| 38 |
- If a port number is not provided then 27017 is assumed. |
| 39 |
type: list |
| 40 |
elements: raw |
| 41 |
validate: |
| 42 |
description: |
| 43 |
- Performs some basic validation on the provided replicaset config. |
| 44 |
type: bool |
| 45 |
default: yes |
| 46 |
arbiter_at_index: |
| 47 |
description: |
| 48 |
- Identifies the position of the member in the array that is an arbiter. |
| 49 |
type: int |
| 50 |
chaining_allowed: |
| 51 |
description: |
| 52 |
- When I(settings.chaining_allowed=true), the replicaset allows secondary members to replicate from other |
| 53 |
secondary members. |
| 54 |
- When I(settings.chaining_allowed=false), secondaries can replicate only from the primary. |
| 55 |
type: bool |
| 56 |
default: yes |
| 57 |
heartbeat_timeout_secs: |
| 58 |
description: |
| 59 |
- Number of seconds that the replicaset members wait for a successful heartbeat from each other. |
| 60 |
- If a member does not respond in time, other members mark the delinquent member as inaccessible. |
| 61 |
- The setting only applies when using I(protocol_version=0). When using I(protocol_version=1) the relevant |
| 62 |
setting is I(settings.election_timeout_millis). |
| 63 |
type: int |
| 64 |
default: 10 |
| 65 |
election_timeout_millis: |
| 66 |
description: |
| 67 |
- The time limit in milliseconds for detecting when a replicaset's primary is unreachable. |
| 68 |
type: int |
| 69 |
default: 10000 |
| 70 |
protocol_version: |
| 71 |
description: Version of the replicaset election protocol. |
| 72 |
type: int |
| 73 |
choices: [ 0, 1 ] |
| 74 |
default: 1 |
| 75 |
reconfigure: |
| 76 |
description: |
| 77 |
- This feature is currently experimental. Please test your scenario thoroughly. |
| 78 |
- Consult the integration test file for supported scenarios - \ |
| 79 |
[Integration tests](https://github.com/ansible-collections/community.mongodb/tree/master/tests/integration/targets/mongodb_replicaset/tasks). \ |
| 80 |
See files prefixed with 330. |
| 81 |
- Whether to perform replicaset reconfiguration actions. |
| 82 |
- Only relevant when the replicaset already exists. |
| 83 |
- Only one member should be removed or added per invocation. |
| 84 |
- Members should be specific as either all strings or all dicts when reconfiguring. |
| 85 |
- Currently no support for replicaset settings document changes. |
| 86 |
- Please always specify ports in the replicaset list when using this feature or some operations may fail. |
| 87 |
type: bool |
| 88 |
default: false |
| 89 |
force: |
| 90 |
description: |
| 91 |
- Only relevant when reconfigure = true. |
| 92 |
- Specify true to force the available replica set members to accept the new configuration. |
| 93 |
- Force reconfiguration can result in unexpected or undesired behavior, including rollback of "majority" committed writes. |
| 94 |
type: bool |
| 95 |
default: false |
| 96 |
max_time_ms: |
| 97 |
description: |
| 98 |
- Specifies a cumulative time limit in milliseconds for processing the replicaset reconfiguration. |
| 99 |
type: int |
| 100 |
default: null |
| 101 |
debug: |
| 102 |
description: |
| 103 |
- Add additonal info for debug. |
| 104 |
type: bool |
| 105 |
default: false |
| 106 |
cluster_cmd: |
| 107 |
description: |
| 108 |
- Command the module should use to obtain information about the MongoDB node we are connecting to. |
| 109 |
type: str |
| 110 |
choices: |
| 111 |
- isMaster |
| 112 |
- hello |
| 113 |
default: hello |
| 114 |
notes: |
| 115 |
- Requires the pymongo Python package on the remote host, version 4+.. This |
| 116 |
can be installed using pip or the OS package manager. |
| 117 |
@see U(http://api.mongodb.org/python/current/installation.html) |
| 118 |
requirements: |
| 119 |
- pymongo |
| 120 |
''' |
| 121 |
|
| 122 |
EXAMPLES = r''' |
| 123 |
# Create a replicaset called 'rs0' with the 3 provided members |
| 124 |
- name: Ensure replicaset rs0 exists |
| 125 |
community.mongodb.mongodb_replicaset: |
| 126 |
login_host: localhost |
| 127 |
login_user: admin |
| 128 |
login_password: admin |
| 129 |
replica_set: rs0 |
| 130 |
members: |
| 131 |
- mongodb1:27017 |
| 132 |
- mongodb2:27017 |
| 133 |
- mongodb3:27017 |
| 134 |
when: groups.mongod.index(inventory_hostname) == 0 |
| 135 |
|
| 136 |
# Create two single-node replicasets on the localhost for testing |
| 137 |
- name: Ensure replicaset rs0 exists |
| 138 |
community.mongodb.mongodb_replicaset: |
| 139 |
login_host: localhost |
| 140 |
login_port: 3001 |
| 141 |
login_user: admin |
| 142 |
login_password: secret |
| 143 |
login_database: admin |
| 144 |
replica_set: rs0 |
| 145 |
members: localhost:3001 |
| 146 |
validate: no |
| 147 |
|
| 148 |
- name: Ensure replicaset rs1 exists |
| 149 |
community.mongodb.mongodb_replicaset: |
| 150 |
login_host: localhost |
| 151 |
login_port: 3002 |
| 152 |
login_user: admin |
| 153 |
login_password: secret |
| 154 |
login_database: admin |
| 155 |
replica_set: rs1 |
| 156 |
members: localhost:3002 |
| 157 |
validate: no |
| 158 |
|
| 159 |
- name: Create a replicaset and use a custom priority for each member |
| 160 |
community.mongodb.mongodb_replicaset: |
| 161 |
login_host: localhost |
| 162 |
login_user: admin |
| 163 |
login_password: admin |
| 164 |
replica_set: rs0 |
| 165 |
members: |
| 166 |
- host: "localhost:3001" |
| 167 |
priority: 1 |
| 168 |
- host: "localhost:3002" |
| 169 |
priority: 0.5 |
| 170 |
- host: "localhost:3003" |
| 171 |
priority: 0.5 |
| 172 |
when: groups.mongod.index(inventory_hostname) == 0 |
| 173 |
|
| 174 |
- name: Create replicaset rs1 with options and member tags |
| 175 |
community.mongodb.mongodb_replicaset: |
| 176 |
login_host: localhost |
| 177 |
login_port: 3001 |
| 178 |
login_database: admin |
| 179 |
replica_set: rs1 |
| 180 |
members: |
| 181 |
- host: "localhost:3001" |
| 182 |
priority: 1 |
| 183 |
tags: |
| 184 |
dc: "east" |
| 185 |
usage: "production" |
| 186 |
- host: "localhost:3002" |
| 187 |
priority: 1 |
| 188 |
tags: |
| 189 |
dc: "east" |
| 190 |
usage: "production" |
| 191 |
- host: "localhost:3003" |
| 192 |
priority: 0 |
| 193 |
hidden: true |
| 194 |
slaveDelay: 3600 |
| 195 |
tags: |
| 196 |
dc: "west" |
| 197 |
usage: "reporting" |
| 198 |
|
| 199 |
- name: Replicaset with one arbiter node (mongodb3 - index is zero-based) |
| 200 |
community.mongodb.mongodb_replicaset: |
| 201 |
login_user: admin |
| 202 |
login_password: admin |
| 203 |
replica_set: rs0 |
| 204 |
members: |
| 205 |
- mongodb1:27017 |
| 206 |
- mongodb2:27017 |
| 207 |
- mongodb3:27017 |
| 208 |
arbiter_at_index: 2 |
| 209 |
when: groups.mongod.index(inventory_hostname) == 0 |
| 210 |
|
| 211 |
- name: Add a new member to a replicaset - Safe for pre-5.0 consult documentation - https://docs.mongodb.com/manual/tutorial/expand-replica-set/ |
| 212 |
block: |
| 213 |
- name: Create replicaset with module - with dicts |
| 214 |
community.mongodb.mongodb_replicaset: |
| 215 |
replica_set: "rs0" |
| 216 |
members: |
| 217 |
- host: localhost:3001 |
| 218 |
- host: localhost:3002 |
| 219 |
- host: localhost:3003 |
| 220 |
|
| 221 |
- name: Wait for the replicaset to stabilise |
| 222 |
community.mongodb.mongodb_status: |
| 223 |
replica_set: "rs0" |
| 224 |
poll: 5 |
| 225 |
interval: 10 |
| 226 |
|
| 227 |
- name: Remove a member from the replicaset |
| 228 |
community.mongodb.mongodb_replicaset: |
| 229 |
replica_set: "rs0" |
| 230 |
reconfigure: yes |
| 231 |
members: |
| 232 |
- host: localhost:3001 |
| 233 |
- host: localhost:3002 |
| 234 |
|
| 235 |
- name: Wait for the replicaset to stabilise after member removal |
| 236 |
community.mongodb.mongodb_status: |
| 237 |
replica_set: "rs0" |
| 238 |
validate: minimal |
| 239 |
poll: 5 |
| 240 |
interval: 10 |
| 241 |
|
| 242 |
- name: Add a member to the replicaset |
| 243 |
community.mongodb.mongodb_replicaset: |
| 244 |
replica_set: "rs0" |
| 245 |
reconfigure: yes |
| 246 |
members: |
| 247 |
- host: localhost:3001 |
| 248 |
- host: localhost:3002 |
| 249 |
- host: localhost:3004 |
| 250 |
hidden: true |
| 251 |
votes: 0 |
| 252 |
priority: 0 |
| 253 |
|
| 254 |
- name: Wait for the replicaset to stabilise after member addition |
| 255 |
community.mongodb.mongodb_status: |
| 256 |
replica_set: "rs0" |
| 257 |
validate: minimal |
| 258 |
poll: 5 |
| 259 |
interval: 30 |
| 260 |
|
| 261 |
- name: Reconfigure the replicaset - Make member 3004 a normal voting member |
| 262 |
community.mongodb.mongodb_replicaset: |
| 263 |
replica_set: "rs0" |
| 264 |
reconfigure: yes |
| 265 |
members: |
| 266 |
- host: localhost:3001 |
| 267 |
- host: localhost:3002 |
| 268 |
- host: localhost:3004 |
| 269 |
hidden: false |
| 270 |
votes: 1 |
| 271 |
priority: 1 |
| 272 |
|
| 273 |
- name: Wait for the replicaset to stabilise |
| 274 |
community.mongodb.mongodb_status: |
| 275 |
replica_set: "rs0" |
| 276 |
poll: 5 |
| 277 |
interval: 30 |
| 278 |
''' |
| 279 |
|
| 280 |
RETURN = r''' |
| 281 |
mongodb_replicaset: |
| 282 |
description: The name of the replicaset that has been created. |
| 283 |
returned: success |
| 284 |
type: str |
| 285 |
reconfigure: |
| 286 |
description: If a replicaset reconfiguration occured. |
| 287 |
returned: On rpelicaset reconfiguration |
| 288 |
type: bool |
| 289 |
''' |
| 290 |
|
| 291 |
from ansible.module_utils.basic import AnsibleModule |
| 292 |
from ansible.module_utils._text import to_native |
| 293 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 294 |
missing_required_lib, |
| 295 |
mongodb_common_argument_spec, |
| 296 |
mongo_auth, |
| 297 |
member_dicts_different, |
| 298 |
lists_are_different, |
| 299 |
PYMONGO_IMP_ERR, |
| 300 |
pymongo_found, |
| 301 |
get_mongodb_client, |
| 302 |
) |
| 303 |
|
| 304 |
|
| 305 |
def get_replicaset_config(client): |
| 306 |
conf = client.admin.command({'replSetGetConfig': 1}) |
| 307 |
return conf['config'] |
| 308 |
|
| 309 |
|
| 310 |
def get_member_names(client): |
| 311 |
conf = get_replicaset_config(client) |
| 312 |
members = [] |
| 313 |
for member in conf['members']: |
| 314 |
members.append(member['host']) |
| 315 |
return members |
| 316 |
|
| 317 |
|
| 318 |
def modify_members(module, config, members): |
| 319 |
""" |
| 320 |
Modifies the members section of the config document as appropriate. |
| 321 |
@module - Ansible module object |
| 322 |
@config - Replicaset config document from MongoDB |
| 323 |
@members - Members config from module |
| 324 |
""" |
| 325 |
try: # refactor repeated code |
| 326 |
from collections import OrderedDict |
| 327 |
except ImportError as excep: |
| 328 |
try: |
| 329 |
from ordereddict import OrderedDict |
| 330 |
except ImportError as excep: |
| 331 |
module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict: %s' |
| 332 |
% to_native(excep)) |
| 333 |
new_member_config = [] # the list of dicts containing the members for the replicaset configuration document |
| 334 |
existing_members = [] # members that are staying in the config |
| 335 |
max_id = 0 |
| 336 |
if all(isinstance(member, str) for member in members): |
| 337 |
for current_member in config['members']: |
| 338 |
if current_member["host"] in members: |
| 339 |
new_member_config.append(current_member) |
| 340 |
existing_members.append(current_member["host"]) |
| 341 |
if current_member["_id"] > max_id: |
| 342 |
max_id = current_member["_id"] |
| 343 |
member_additions = list(set(members) - set(existing_members)) |
| 344 |
if len(member_additions) > 0: |
| 345 |
for member in member_additions: |
| 346 |
if ':' not in member: # No port supplied. Assume 27017 |
| 347 |
member += ":27017" |
| 348 |
new_member_config.append(OrderedDict([("_id", max_id + 1), ("host", member)])) |
| 349 |
max_id += 1 |
| 350 |
config["members"] = new_member_config |
| 351 |
elif all(isinstance(member, dict) for member in members): |
| 352 |
# We need to put the _id values in into the matching document and generate them for new hosts |
| 353 |
# TODO: https://docs.mongodb.com/manual/reference/replica-configuration/#mongodb-rsconf-rsconf.members-n-._id |
| 354 |
# Maybe we can add a new member id parameter value, stick with the incrementing for now |
| 355 |
# Perhaps even save this in the mongodb instance? |
| 356 |
|
| 357 |
# first get all the existing members of the replicaset |
| 358 |
new_member_config = [] |
| 359 |
existing_members = {} |
| 360 |
matched_members = [] # members that have been supplied by the moduel and matched with existing members |
| 361 |
max_id = 0 |
| 362 |
for member in config["members"]: |
| 363 |
existing_members[member["host"]] = member["_id"] |
| 364 |
if member["_id"] > max_id: |
| 365 |
max_id = member["_id"] |
| 366 |
# append existing members with the appropriate _id |
| 367 |
for member in members: |
| 368 |
if member["host"] in existing_members: |
| 369 |
member["_id"] = existing_members[member["host"]] |
| 370 |
matched_members.append(member["host"]) |
| 371 |
new_member_config.append(member) |
| 372 |
for member in members: |
| 373 |
if member["host"] not in matched_members: # new member , append and increment id |
| 374 |
max_id = max_id + 1 |
| 375 |
member["_id"] = max_id |
| 376 |
new_member_config.append(member) |
| 377 |
config["members"] = new_member_config |
| 378 |
else: |
| 379 |
module.fail_json(msg="All items in members must be either of type dict of str") |
| 380 |
return config |
| 381 |
|
| 382 |
|
| 383 |
def replicaset_reconfigure(module, client, config, force, max_time_ms): |
| 384 |
|
| 385 |
config['version'] += 1 |
| 386 |
|
| 387 |
try: |
| 388 |
from collections import OrderedDict |
| 389 |
except ImportError as excep: |
| 390 |
try: |
| 391 |
from ordereddict import OrderedDict |
| 392 |
except ImportError as excep: |
| 393 |
module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict: %s' |
| 394 |
% to_native(excep)) |
| 395 |
|
| 396 |
cmd_doc = OrderedDict([("replSetReconfig", config), |
| 397 |
("force", force)]) |
| 398 |
if max_time_ms is not None: |
| 399 |
cmd_doc.update({"maxTimeMS": max_time_ms}) |
| 400 |
|
| 401 |
client.admin.command(cmd_doc) |
| 402 |
# return result |
| 403 |
|
| 404 |
|
| 405 |
def replicaset_find(client, cluster_cmd): |
| 406 |
"""Check if a replicaset exists. |
| 407 |
|
| 408 |
Args: |
| 409 |
client (cursor): Mongodb cursor on admin database. |
| 410 |
cluster_cmd (str): Either isMaster or hello |
| 411 |
|
| 412 |
Returns: |
| 413 |
str: when the node is a member of a replicaset , False otherwise. |
| 414 |
""" |
| 415 |
doc = client['admin'].command(cluster_cmd) |
| 416 |
if 'setName' in doc: |
| 417 |
return str(doc['setName']) |
| 418 |
return False |
| 419 |
|
| 420 |
|
| 421 |
def replicaset_add(module, client, replica_set, members, arbiter_at_index, protocol_version, |
| 422 |
chaining_allowed, heartbeat_timeout_secs, election_timeout_millis): |
| 423 |
|
| 424 |
try: |
| 425 |
from collections import OrderedDict |
| 426 |
except ImportError as excep: |
| 427 |
try: |
| 428 |
from ordereddict import OrderedDict |
| 429 |
except ImportError as excep: |
| 430 |
module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict: %s' |
| 431 |
% to_native(excep)) |
| 432 |
|
| 433 |
members_dict_list = [] |
| 434 |
index = 0 |
| 435 |
settings = { |
| 436 |
"chainingAllowed": bool(chaining_allowed), |
| 437 |
} |
| 438 |
if protocol_version == 0: |
| 439 |
settings['heartbeatTimeoutSecs'] = heartbeat_timeout_secs |
| 440 |
else: |
| 441 |
settings['electionTimeoutMillis'] = election_timeout_millis |
| 442 |
for member in members: |
| 443 |
if isinstance(member, str): |
| 444 |
if ':' not in member: # No port supplied. Assume 27017 |
| 445 |
member += ":27017" |
| 446 |
members_dict_list.append(OrderedDict([("_id", int(index)), ("host", member)])) |
| 447 |
if index == arbiter_at_index: |
| 448 |
members_dict_list[index]['arbiterOnly'] = True |
| 449 |
index += 1 |
| 450 |
elif isinstance(member, dict): |
| 451 |
hostname = member["host"] |
| 452 |
if ':' not in hostname: |
| 453 |
hostname += ":27017" |
| 454 |
members_dict_list.append(OrderedDict([("_id", int(index)), ("host", hostname)])) |
| 455 |
for key in list(member.keys()): |
| 456 |
if key != "host": |
| 457 |
members_dict_list[index][key] = member[key] |
| 458 |
if index == arbiter_at_index: |
| 459 |
members_dict_list[index]['arbiterOnly'] = True |
| 460 |
index += 1 |
| 461 |
else: |
| 462 |
raise ValueError("member should be a str or dict. Instead found: {0}".format(str(type(members)))) |
| 463 |
|
| 464 |
conf = OrderedDict([("_id", replica_set), |
| 465 |
("protocolVersion", protocol_version), |
| 466 |
("members", members_dict_list), |
| 467 |
("settings", settings)]) |
| 468 |
try: |
| 469 |
client["admin"].command('replSetInitiate', conf) |
| 470 |
except Exception as excep: |
| 471 |
raise Exception("Some problem {0} | {1}".format(str(excep), str(conf))) |
| 472 |
|
| 473 |
|
| 474 |
def replicaset_remove(module, client, replica_set): |
| 475 |
raise NotImplementedError |
| 476 |
|
| 477 |
|
| 478 |
def modify_members_flow(module, client, members, result): |
| 479 |
debug = module.params['debug'] |
| 480 |
force = module.params['force'] |
| 481 |
max_time_ms = module.params['max_time_ms'] |
| 482 |
diff = False |
| 483 |
modified_config = None |
| 484 |
config = None |
| 485 |
|
| 486 |
try: |
| 487 |
config = get_replicaset_config(client) |
| 488 |
except Exception as excep: |
| 489 |
module.fail_json(msg="Unable to get replicaset configuration {0}".format(excep)) |
| 490 |
|
| 491 |
if isinstance(members[0], str): |
| 492 |
diff = lists_are_different(members, get_member_names(client)) |
| 493 |
elif isinstance(members[0], dict): |
| 494 |
diff = member_dicts_different(config, members) |
| 495 |
else: |
| 496 |
module.fail_json(msg="members must be either str or dict") |
| 497 |
if diff: |
| 498 |
if not module.check_mode: |
| 499 |
try: |
| 500 |
modified_config = modify_members(module, config, members) |
| 501 |
if debug: |
| 502 |
result['config'] = str(config) |
| 503 |
result['modified_config'] = str(modified_config) |
| 504 |
replicaset_reconfigure(module, client, modified_config, force, max_time_ms) |
| 505 |
except Exception as excep: |
| 506 |
module.fail_json(msg="Failed reconfiguring replicaset {0}, config doc {1}".format(excep, modified_config)) |
| 507 |
result['changed'] = True |
| 508 |
result['msg'] = "replicaset reconfigured" |
| 509 |
else: |
| 510 |
result['changed'] = False |
| 511 |
return result |
| 512 |
|
| 513 |
# ========================================= |
| 514 |
# Module execution. |
| 515 |
# |
| 516 |
|
| 517 |
|
| 518 |
def main(): |
| 519 |
argument_spec = mongodb_common_argument_spec() |
| 520 |
argument_spec.update( |
| 521 |
arbiter_at_index=dict(type='int'), |
| 522 |
chaining_allowed=dict(type='bool', default=True), |
| 523 |
election_timeout_millis=dict(type='int', default=10000), |
| 524 |
heartbeat_timeout_secs=dict(type='int', default=10), |
| 525 |
members=dict(type='list', elements='raw'), |
| 526 |
protocol_version=dict(type='int', default=1, choices=[0, 1]), |
| 527 |
replica_set=dict(type='str', default="rs0"), |
| 528 |
validate=dict(type='bool', default=True), |
| 529 |
reconfigure=dict(type='bool', default=False), |
| 530 |
force=dict(type='bool', default=False), |
| 531 |
max_time_ms=dict(type='int', default=None), |
| 532 |
debug=dict(type='bool', default=False), |
| 533 |
cluster_cmd=dict(type='str', choices=['isMaster', 'hello'], default='hello') |
| 534 |
) |
| 535 |
module = AnsibleModule( |
| 536 |
argument_spec=argument_spec, |
| 537 |
supports_check_mode=True, |
| 538 |
required_together=[['login_user', 'login_password']], |
| 539 |
) |
| 540 |
|
| 541 |
if not pymongo_found: |
| 542 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 543 |
exception=PYMONGO_IMP_ERR) |
| 544 |
|
| 545 |
replica_set = module.params['replica_set'] |
| 546 |
members = module.params['members'] |
| 547 |
arbiter_at_index = module.params['arbiter_at_index'] |
| 548 |
validate = module.params['validate'] |
| 549 |
protocol_version = module.params['protocol_version'] |
| 550 |
chaining_allowed = module.params['chaining_allowed'] |
| 551 |
heartbeat_timeout_secs = module.params['heartbeat_timeout_secs'] |
| 552 |
election_timeout_millis = module.params['election_timeout_millis'] |
| 553 |
reconfigure = module.params['reconfigure'] |
| 554 |
force = module.params['force'] # TODO tidy this stuff up |
| 555 |
max_time_ms = module.params['max_time_ms'] |
| 556 |
debug = module.params['debug'] |
| 557 |
cluster_cmd = module.params['cluster_cmd'] |
| 558 |
|
| 559 |
# Count voting members |
| 560 |
voting_members = sum([1 if not isinstance(m, dict) or m.get("votes", 1) == 1 else 0 for m in members]) |
| 561 |
|
| 562 |
if validate and reconfigure is False: |
| 563 |
if len(members) <= 2 or voting_members % 2 == 0: |
| 564 |
module.fail_json(msg="MongoDB Replicaset validation failed. Invalid number of replicaset members.") |
| 565 |
if arbiter_at_index is not None and len(members) - 1 < arbiter_at_index: |
| 566 |
module.fail_json(msg="MongoDB Replicaset validation failed. Invalid arbiter index.") |
| 567 |
|
| 568 |
result = dict( |
| 569 |
changed=False, |
| 570 |
replica_set=replica_set, |
| 571 |
) |
| 572 |
|
| 573 |
try: |
| 574 |
client = get_mongodb_client(module, directConnection=True) |
| 575 |
except Exception as e: |
| 576 |
module.fail_json(msg='Unable to connect to database: %s' % to_native(e)) |
| 577 |
|
| 578 |
try: |
| 579 |
rs = replicaset_find(client, cluster_cmd) # does not require auth |
| 580 |
except Exception as e: |
| 581 |
module.fail_json(msg='Unable to connect to query replicaset: %s' % to_native(e)) |
| 582 |
|
| 583 |
if isinstance(rs, str): |
| 584 |
if replica_set == rs: |
| 585 |
if reconfigure: |
| 586 |
client = mongo_auth(module, client) |
| 587 |
result = modify_members_flow(module, client, members, result) |
| 588 |
else: |
| 589 |
result['changed'] = False |
| 590 |
result['replica_set'] = rs |
| 591 |
module.exit_json(**result) |
| 592 |
else: |
| 593 |
module.fail_json(msg="The replica_set name of {0} does not match the expected: {1}".format(rs, replica_set)) |
| 594 |
else: # replicaset does not exist |
| 595 |
|
| 596 |
# Some validation stuff |
| 597 |
if len(replica_set) == 0: |
| 598 |
module.fail_json(msg="Parameter replica_set must not be an empty string") |
| 599 |
|
| 600 |
if module.check_mode is False: |
| 601 |
try: |
| 602 |
replicaset_add(module, client, replica_set, members, |
| 603 |
arbiter_at_index, protocol_version, |
| 604 |
chaining_allowed, heartbeat_timeout_secs, |
| 605 |
election_timeout_millis) |
| 606 |
result['changed'] = True |
| 607 |
except Exception as e: |
| 608 |
module.fail_json(msg='Unable to create replica_set: %s' % to_native(e)) |
| 609 |
else: |
| 610 |
result['changed'] = True |
| 611 |
|
| 612 |
module.exit_json(**result) |
| 613 |
|
| 614 |
|
| 615 |
if __name__ == '__main__': |
| 616 |
main() |