| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# (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 = ''' |
| 11 |
--- |
| 12 |
module: mongodb_shard |
| 13 |
short_description: Add or remove shards from a MongoDB Cluster |
| 14 |
description: |
| 15 |
- Add or remove shards from a MongoDB Cluster. |
| 16 |
author: Rhys Campbell (@rhysmeister) |
| 17 |
version_added: "1.0.0" |
| 18 |
|
| 19 |
extends_documentation_fragment: |
| 20 |
- community.mongodb.login_options |
| 21 |
- community.mongodb.ssl_options |
| 22 |
|
| 23 |
options: |
| 24 |
shard: |
| 25 |
description: |
| 26 |
- The shard connection string. |
| 27 |
- Should be supplied in the form <replicaset>/host:port as detailed in U(https://docs.mongodb.com/manual/tutorial/add-shards-to-shard-cluster/). |
| 28 |
- For example rs0/example1.mongodb.com:27017. |
| 29 |
required: true |
| 30 |
type: str |
| 31 |
sharded_databases: |
| 32 |
description: |
| 33 |
- Enable sharding on the listed database. |
| 34 |
- Can be supplied as a string or a list of strings. |
| 35 |
- Sharding cannot be disabled on a database. |
| 36 |
- Starting in MongoDB 6.0, the enableSharding command is no longer required to shard a collection and this parameter is ignored. |
| 37 |
required: false |
| 38 |
type: raw |
| 39 |
mongos_process: |
| 40 |
description: |
| 41 |
- Provide a custom name for the mongos process you are connecting to. |
| 42 |
- Most users can ignore this setting. |
| 43 |
required: false |
| 44 |
type: str |
| 45 |
default: "mongos" |
| 46 |
state: |
| 47 |
description: |
| 48 |
- Whether the shard should be present or absent from the Cluster. |
| 49 |
required: false |
| 50 |
type: str |
| 51 |
default: present |
| 52 |
choices: |
| 53 |
- "absent" |
| 54 |
- "present" |
| 55 |
|
| 56 |
notes: |
| 57 |
- Requires the pymongo Python package on the remote host, version 4+. |
| 58 |
requirements: [ pymongo ] |
| 59 |
''' |
| 60 |
|
| 61 |
EXAMPLES = ''' |
| 62 |
- name: Add a replicaset shard named rs1 with a member running on port 27018 on mongodb0.example.net |
| 63 |
community.mongodb.mongodb_shard: |
| 64 |
login_user: admin |
| 65 |
login_password: admin |
| 66 |
shard: "rs1/mongodb0.example.net:27018" |
| 67 |
state: present |
| 68 |
|
| 69 |
- name: Add a standalone mongod shard running on port 27018 of mongodb0.example.net |
| 70 |
community.mongodb.mongodb_shard: |
| 71 |
login_user: admin |
| 72 |
login_password: admin |
| 73 |
shard: "mongodb0.example.net:27018" |
| 74 |
state: present |
| 75 |
|
| 76 |
- name: To remove a shard called 'rs1' |
| 77 |
community.mongodb.mongodb_shard: |
| 78 |
login_user: admin |
| 79 |
login_password: admin |
| 80 |
shard: rs1 |
| 81 |
state: absent |
| 82 |
|
| 83 |
# Single node shard running on localhost |
| 84 |
- name: Ensure shard rs0 exists |
| 85 |
community.mongodb.mongodb_shard: |
| 86 |
login_user: admin |
| 87 |
login_password: secret |
| 88 |
shard: "rs0/localhost:3001" |
| 89 |
state: present |
| 90 |
|
| 91 |
# Single node shard running on localhost |
| 92 |
- name: Ensure shard rs1 exists |
| 93 |
community.mongodb.mongodb_shard: |
| 94 |
login_user: admin |
| 95 |
login_password: secret |
| 96 |
shard: "rs1/localhost:3002" |
| 97 |
state: present |
| 98 |
|
| 99 |
# Enable sharding on a few databases when creating the shard |
| 100 |
- name: To remove a shard called 'rs1' |
| 101 |
community.mongodb.mongodb_shard: |
| 102 |
login_user: admin |
| 103 |
login_password: admin |
| 104 |
shard: rs1 |
| 105 |
sharded_databases: |
| 106 |
- db1 |
| 107 |
- db2 |
| 108 |
state: present |
| 109 |
''' |
| 110 |
|
| 111 |
RETURN = ''' |
| 112 |
mongodb_shard: |
| 113 |
description: The name of the shard to create. |
| 114 |
returned: success |
| 115 |
type: str |
| 116 |
sharded_enabled: |
| 117 |
description: Databases that have had sharding enabled during module execution. |
| 118 |
returned: success when sharding is enabled |
| 119 |
type: list |
| 120 |
''' |
| 121 |
|
| 122 |
import traceback |
| 123 |
|
| 124 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 125 |
from ansible.module_utils._text import to_native |
| 126 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 127 |
missing_required_lib, |
| 128 |
mongodb_common_argument_spec, |
| 129 |
mongo_auth, |
| 130 |
PYMONGO_IMP_ERR, |
| 131 |
pymongo_found, |
| 132 |
get_mongodb_client, |
| 133 |
check_srv_version |
| 134 |
) |
| 135 |
|
| 136 |
|
| 137 |
def shard_find(client, shard): |
| 138 |
"""Check if a shard exists. |
| 139 |
|
| 140 |
Args: |
| 141 |
client (cursor): Mongodb cursor on admin database. |
| 142 |
shard (str): shard to check. |
| 143 |
|
| 144 |
Returns: |
| 145 |
dict: when user exists, False otherwise. |
| 146 |
""" |
| 147 |
if '/' in shard: |
| 148 |
s = shard.split('/')[0] |
| 149 |
else: |
| 150 |
s = shard |
| 151 |
for shard in client["config"].shards.find({"_id": s}): |
| 152 |
return shard |
| 153 |
return False |
| 154 |
|
| 155 |
|
| 156 |
def shard_add(client, shard): |
| 157 |
try: |
| 158 |
sh = client["admin"].command('addShard', shard) |
| 159 |
except Exception as excep: |
| 160 |
raise excep |
| 161 |
return sh |
| 162 |
|
| 163 |
|
| 164 |
def shard_remove(client, shard): |
| 165 |
try: |
| 166 |
sh = client["admin"].command('removeShard', shard) |
| 167 |
except Exception as excep: |
| 168 |
raise excep |
| 169 |
return sh |
| 170 |
|
| 171 |
|
| 172 |
def sharded_dbs(client): |
| 173 |
''' |
| 174 |
Returns the sharded databases |
| 175 |
Args: |
| 176 |
client (cursor): Mongodb cursor on admin database. |
| 177 |
Returns: |
| 178 |
a list of database names that are sharded |
| 179 |
''' |
| 180 |
sharded_databases = [] |
| 181 |
for entry in client["config"].databases.find({"partitioned": True}, {"_id": 1}): |
| 182 |
sharded_databases.append(entry["_id"]) |
| 183 |
return sharded_databases |
| 184 |
|
| 185 |
|
| 186 |
def enable_database_sharding(client, database): |
| 187 |
''' |
| 188 |
Enables sharding on a database |
| 189 |
Args: |
| 190 |
client (cursor): Mongodb cursor on admin database. |
| 191 |
Returns: |
| 192 |
true on success, false on failure |
| 193 |
''' |
| 194 |
s = False |
| 195 |
db = client["admin"].command('enableSharding', database) |
| 196 |
if db: |
| 197 |
s = True |
| 198 |
return s |
| 199 |
|
| 200 |
|
| 201 |
def any_dbs_to_shard(client, sharded_databases): |
| 202 |
''' |
| 203 |
Return a list of databases that need to have sharding enabled |
| 204 |
sharded_databases - Provided by module |
| 205 |
cluster_sharded_databases - List of sharded dbs from the mongos |
| 206 |
''' |
| 207 |
dbs_to_shard = [] |
| 208 |
cluster_sharded_databases = sharded_dbs(client) |
| 209 |
for db in sharded_databases: |
| 210 |
if db not in cluster_sharded_databases: |
| 211 |
dbs_to_shard.append(db) |
| 212 |
return dbs_to_shard |
| 213 |
|
| 214 |
|
| 215 |
# ========================================= |
| 216 |
# Module execution. |
| 217 |
# |
| 218 |
|
| 219 |
|
| 220 |
def main(): |
| 221 |
argument_spec = mongodb_common_argument_spec() |
| 222 |
argument_spec.update( |
| 223 |
mongos_process=dict(type='str', required=False, default="mongos"), |
| 224 |
shard=dict(type='str', required=True), |
| 225 |
sharded_databases=dict(type="raw", required=False), |
| 226 |
state=dict(type='str', required=False, default='present', choices=['absent', 'present']) |
| 227 |
) |
| 228 |
module = AnsibleModule( |
| 229 |
argument_spec=argument_spec, |
| 230 |
supports_check_mode=True, |
| 231 |
required_together=[['login_user', 'login_password']], |
| 232 |
) |
| 233 |
|
| 234 |
if not pymongo_found: |
| 235 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 236 |
exception=PYMONGO_IMP_ERR) |
| 237 |
|
| 238 |
login_host = module.params['login_host'] |
| 239 |
login_port = module.params['login_port'] |
| 240 |
shard = module.params['shard'] |
| 241 |
state = module.params['state'] |
| 242 |
sharded_databases = module.params['sharded_databases'] |
| 243 |
mongos_process = module.params['mongos_process'] |
| 244 |
|
| 245 |
try: |
| 246 |
client = get_mongodb_client(module) |
| 247 |
client = mongo_auth(module, client) |
| 248 |
except Exception as excep: |
| 249 |
module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep)) |
| 250 |
|
| 251 |
try: |
| 252 |
if client["admin"].command("serverStatus")["process"] != mongos_process: |
| 253 |
module.fail_json(msg="Process running on {0}:{1} is not a {2}".format(login_host, login_port, mongos_process)) |
| 254 |
|
| 255 |
dbs_to_shard = [] |
| 256 |
|
| 257 |
if sharded_databases is not None and int(check_srv_version(module, client)[0]) < 6: |
| 258 |
if isinstance(sharded_databases, str): |
| 259 |
sharded_databases = list(sharded_databases) |
| 260 |
dbs_to_shard = any_dbs_to_shard(client, sharded_databases) |
| 261 |
|
| 262 |
if module.check_mode: |
| 263 |
if state == "present": |
| 264 |
changed = False |
| 265 |
if not shard_find(client, shard) or len(dbs_to_shard) > 0: |
| 266 |
changed = True |
| 267 |
elif state == "absent": |
| 268 |
if not shard_find(client, shard): |
| 269 |
changed = False |
| 270 |
else: |
| 271 |
changed = True |
| 272 |
else: |
| 273 |
if state == "present": |
| 274 |
if not shard_find(client, shard): |
| 275 |
shard_add(client, shard) |
| 276 |
changed = True |
| 277 |
else: |
| 278 |
changed = False |
| 279 |
if len(dbs_to_shard) > 0: |
| 280 |
for db in dbs_to_shard: |
| 281 |
enable_database_sharding(client, db) |
| 282 |
changed = True |
| 283 |
elif state == "absent": |
| 284 |
if shard_find(client, shard): |
| 285 |
shard_remove(client, shard) |
| 286 |
changed = True |
| 287 |
else: |
| 288 |
changed = False |
| 289 |
except Exception as e: |
| 290 |
action = "add" |
| 291 |
if state == "absent": |
| 292 |
action = "remove" |
| 293 |
module.fail_json(msg='Unable to {0} shard: %s'.format(action) % to_native(e), exception=traceback.format_exc()) |
| 294 |
|
| 295 |
result = { |
| 296 |
"changed": changed, |
| 297 |
"shard": shard, |
| 298 |
} |
| 299 |
if len(dbs_to_shard) > 0: |
| 300 |
result['sharded_enabled'] = dbs_to_shard |
| 301 |
|
| 302 |
module.exit_json(**result) |
| 303 |
|
| 304 |
|
| 305 |
if __name__ == '__main__': |
| 306 |
main() |