| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2021, Rhys Campbell (@rhysmeister) <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
|
| 11 |
DOCUMENTATION = r''' |
| 12 |
--- |
| 13 |
module: mongodb_schema |
| 14 |
|
| 15 |
short_description: Manages MongoDB Document Schema Validators. |
| 16 |
|
| 17 |
description: |
| 18 |
- Manages MongoDB Document Schema Validators. |
| 19 |
- Create, update and remove Validators on a collection. |
| 20 |
- Supports the entire range of jsonSchema keywords. |
| 21 |
- See [jsonSchema Available Keywords](https://docs.mongodb.com/manual/reference/operator/query/jsonSchema/#available-keywords) for details. |
| 22 |
|
| 23 |
author: Rhys Campbell (@rhysmeister) |
| 24 |
version_added: "1.3.0" |
| 25 |
|
| 26 |
extends_documentation_fragment: |
| 27 |
- community.mongodb.login_options |
| 28 |
- community.mongodb.ssl_options |
| 29 |
|
| 30 |
options: |
| 31 |
db: |
| 32 |
description: |
| 33 |
- The database to work with. |
| 34 |
required: yes |
| 35 |
type: str |
| 36 |
collection: |
| 37 |
description: |
| 38 |
- The collection to work with. |
| 39 |
required: yes |
| 40 |
type: str |
| 41 |
required: |
| 42 |
description: |
| 43 |
- List of fields that are required. |
| 44 |
type: list |
| 45 |
elements: str |
| 46 |
properties: |
| 47 |
description: |
| 48 |
- Individual property specification. |
| 49 |
type: dict |
| 50 |
default: {} |
| 51 |
action: |
| 52 |
description: |
| 53 |
- The validation action for MongoDB to perform when handling invalid documents. |
| 54 |
type: str |
| 55 |
choices: |
| 56 |
- "error" |
| 57 |
- "warn" |
| 58 |
default: "error" |
| 59 |
level: |
| 60 |
description: |
| 61 |
- The validation level MongoDB should apply when updating existing documents. |
| 62 |
type: str |
| 63 |
choices: |
| 64 |
- "strict" |
| 65 |
- "moderate" |
| 66 |
default: "strict" |
| 67 |
replica_set: |
| 68 |
description: |
| 69 |
- Replicaset name. |
| 70 |
type: str |
| 71 |
default: null |
| 72 |
state: |
| 73 |
description: |
| 74 |
- The state of the validator. |
| 75 |
type: str |
| 76 |
choices: |
| 77 |
- "present" |
| 78 |
- "absent" |
| 79 |
default: "present" |
| 80 |
debug: |
| 81 |
description: |
| 82 |
- Enable additional debugging output. |
| 83 |
type: bool |
| 84 |
default: false |
| 85 |
|
| 86 |
notes: |
| 87 |
- Requires the pymongo Python package on the remote host, version 4+. |
| 88 |
|
| 89 |
requirements: |
| 90 |
- pymongo |
| 91 |
''' |
| 92 |
|
| 93 |
EXAMPLES = r''' |
| 94 |
--- |
| 95 |
- name: Require that an email address field is in every document |
| 96 |
community.mongodb.mongodb_schema: |
| 97 |
collection: contacts |
| 98 |
db: rhys |
| 99 |
required: |
| 100 |
- email |
| 101 |
|
| 102 |
- name: Remove a schema rule |
| 103 |
community.mongodb.mongodb_schema: |
| 104 |
collection: contacts |
| 105 |
db: rhys |
| 106 |
state: absent |
| 107 |
|
| 108 |
|
| 109 |
- name: More advanced example using properties |
| 110 |
community.mongodb.mongodb_schema: |
| 111 |
collection: contacts |
| 112 |
db: rhys |
| 113 |
properties: |
| 114 |
email: |
| 115 |
maxLength: 150 |
| 116 |
minLength: 5 |
| 117 |
options: |
| 118 |
bsonType: array |
| 119 |
maxItems: 10 |
| 120 |
minItems: 5 |
| 121 |
uniqueItems: true |
| 122 |
status: |
| 123 |
bsonType: string |
| 124 |
description: "can only be ACTIVE or DISABLED" |
| 125 |
enum: |
| 126 |
- ACTIVE |
| 127 |
- DISABLED |
| 128 |
year: |
| 129 |
bsonType: int |
| 130 |
description: "must be an integer from 2021 to 3020" |
| 131 |
exclusiveMaximum: false |
| 132 |
maximum: 3020 |
| 133 |
minimum: 2021 |
| 134 |
required: |
| 135 |
- email |
| 136 |
- first_name |
| 137 |
- last_name |
| 138 |
''' |
| 139 |
|
| 140 |
RETURN = r''' |
| 141 |
changed: |
| 142 |
description: If the module caused a change. |
| 143 |
returned: on success |
| 144 |
type: bool |
| 145 |
msg: |
| 146 |
description: Status message. |
| 147 |
returned: always |
| 148 |
type: str |
| 149 |
validator: |
| 150 |
description: The validator document as read from the instance. |
| 151 |
returned: when debug is true |
| 152 |
type: dict |
| 153 |
module_config: |
| 154 |
description: The validator document as indicated by the module invocation. |
| 155 |
returned: when debug is true |
| 156 |
type: dict |
| 157 |
''' |
| 158 |
|
| 159 |
from ansible.module_utils.basic import AnsibleModule |
| 160 |
from ansible.module_utils._text import to_native |
| 161 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 162 |
missing_required_lib, |
| 163 |
mongodb_common_argument_spec, |
| 164 |
mongo_auth, |
| 165 |
PYMONGO_IMP_ERR, |
| 166 |
pymongo_found, |
| 167 |
get_mongodb_client, |
| 168 |
) |
| 169 |
import json |
| 170 |
|
| 171 |
|
| 172 |
has_ordereddict = False |
| 173 |
try: |
| 174 |
from collections import OrderedDict |
| 175 |
has_ordereddict = True |
| 176 |
except ImportError as excep: |
| 177 |
try: |
| 178 |
from ordereddict import OrderedDict |
| 179 |
has_ordereddict = True |
| 180 |
except ImportError as excep: |
| 181 |
pass |
| 182 |
|
| 183 |
|
| 184 |
def get_validator(client, db, collection): |
| 185 |
validator = None |
| 186 |
cmd_doc = OrderedDict([ |
| 187 |
('listCollections', 1), |
| 188 |
('filter', {"name": collection}) |
| 189 |
]) |
| 190 |
doc = None |
| 191 |
results = client[db].command(cmd_doc)["cursor"]["firstBatch"] |
| 192 |
if len(results) > 0: |
| 193 |
doc = results[0] |
| 194 |
if doc is not None and 'options' in doc and 'validator' in doc['options']: |
| 195 |
validator = doc['options']['validator']["$jsonSchema"] |
| 196 |
if 'validationAction' in doc['options']: |
| 197 |
validator['validationAction'] = doc['options']['validationAction'] |
| 198 |
if 'validationLevel' in doc['options']: |
| 199 |
validator['validationLevel'] = doc['options']['validationLevel'] |
| 200 |
return validator |
| 201 |
|
| 202 |
|
| 203 |
def validator_is_different(client, db, collection, required, properties, action, level): |
| 204 |
is_different = False |
| 205 |
validator = get_validator(client, db, collection) |
| 206 |
if validator is not None: |
| 207 |
if sorted(required) != sorted(validator.get('required', [])): |
| 208 |
is_different = True |
| 209 |
if action != validator.get('validationAction', 'error'): |
| 210 |
is_different = True |
| 211 |
if level != validator.get('validationLevel', 'strict'): |
| 212 |
is_different = True |
| 213 |
dict1 = json.dumps(properties, sort_keys=True) |
| 214 |
dict2 = json.dumps(validator.get('properties', {}), sort_keys=True) |
| 215 |
if dict1 != dict2: |
| 216 |
is_different = True |
| 217 |
else: |
| 218 |
is_different = True |
| 219 |
return is_different |
| 220 |
|
| 221 |
|
| 222 |
def add_validator(client, db, collection, required, properties, action, level): |
| 223 |
cmd_doc = OrderedDict([ |
| 224 |
('collMod', collection), |
| 225 |
('validator', {'$jsonSchema': {"bsonType": "object", |
| 226 |
"required": required, |
| 227 |
"properties": properties}}), |
| 228 |
('validationAction', action), |
| 229 |
('validationLevel', level) |
| 230 |
]) |
| 231 |
if collection not in client[db].list_collection_names(): |
| 232 |
client[db].create_collection(collection) |
| 233 |
client[db].command(cmd_doc) |
| 234 |
|
| 235 |
|
| 236 |
def remove_validator(client, db, collection): |
| 237 |
cmd_doc = OrderedDict([ |
| 238 |
('collMod', collection), |
| 239 |
('validator', {}), |
| 240 |
('validationLevel', "off") |
| 241 |
]) |
| 242 |
client[db].command(cmd_doc) |
| 243 |
|
| 244 |
|
| 245 |
# ================ |
| 246 |
# Module execution |
| 247 |
# |
| 248 |
|
| 249 |
def main(): |
| 250 |
argument_spec = mongodb_common_argument_spec() |
| 251 |
argument_spec.update( |
| 252 |
db=dict(type='str', required=True), |
| 253 |
collection=dict(type='str', required=True), |
| 254 |
required=dict(type='list', elements='str'), |
| 255 |
properties=dict(type='dict', default={}), |
| 256 |
action=dict(type='str', choices=['error', 'warn'], default="error"), |
| 257 |
level=dict(type='str', choices=['strict', 'moderate'], default="strict"), |
| 258 |
state=dict(type='str', choices=['present', 'absent'], default='present'), |
| 259 |
debug=dict(type='bool', default=False), |
| 260 |
replica_set=dict(type='str', default=None), |
| 261 |
) |
| 262 |
module = AnsibleModule( |
| 263 |
argument_spec=argument_spec, |
| 264 |
supports_check_mode=True, |
| 265 |
required_together=[['login_user', 'login_password']], |
| 266 |
required_if=[("state", "present", ("db", "collection"))] |
| 267 |
) |
| 268 |
|
| 269 |
if not has_ordereddict: |
| 270 |
module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict') |
| 271 |
|
| 272 |
if not pymongo_found: |
| 273 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 274 |
exception=PYMONGO_IMP_ERR) |
| 275 |
|
| 276 |
db = module.params['db'] |
| 277 |
collection = module.params['collection'] |
| 278 |
required = module.params['required'] |
| 279 |
properties = module.params['properties'] |
| 280 |
action = module.params['action'] |
| 281 |
level = module.params['level'] |
| 282 |
state = module.params['state'] |
| 283 |
debug = module.params['debug'] |
| 284 |
|
| 285 |
try: |
| 286 |
client = get_mongodb_client(module) |
| 287 |
client = mongo_auth(module, client) |
| 288 |
except Exception as e: |
| 289 |
module.fail_json(msg='Unable to connect to database: %s' % to_native(e)) |
| 290 |
|
| 291 |
result = dict( |
| 292 |
changed=False, |
| 293 |
) |
| 294 |
|
| 295 |
validator = get_validator(client, db, collection) |
| 296 |
if state == "present": |
| 297 |
if validator is not None: |
| 298 |
diff = validator_is_different(client, db, collection, required, |
| 299 |
properties, action, level) |
| 300 |
if diff: |
| 301 |
if not module.check_mode: |
| 302 |
add_validator(client, |
| 303 |
db, |
| 304 |
collection, |
| 305 |
required, |
| 306 |
properties, |
| 307 |
action, |
| 308 |
level) |
| 309 |
result['changed'] = True |
| 310 |
result['msg'] = "The validator was updated on the given collection" |
| 311 |
else: |
| 312 |
result['changed'] = False |
| 313 |
result['msg'] = "The validator exists as configured on the given collection" |
| 314 |
else: |
| 315 |
if not module.check_mode: |
| 316 |
add_validator(client, |
| 317 |
db, |
| 318 |
collection, |
| 319 |
required, |
| 320 |
properties, |
| 321 |
action, |
| 322 |
level) |
| 323 |
result['changed'] = True |
| 324 |
result['msg'] = "The validator has been added to the given collection" |
| 325 |
elif state == "absent": |
| 326 |
if validator is None: |
| 327 |
result['changed'] = False |
| 328 |
result['msg'] = "A validator does not exist on the given collection." |
| 329 |
else: |
| 330 |
if not module.check_mode: |
| 331 |
remove_validator(client, db, collection) |
| 332 |
result['changed'] = True |
| 333 |
result['msg'] = "The validator has been removed from the given collection" |
| 334 |
|
| 335 |
if debug: |
| 336 |
result['validator'] = validator |
| 337 |
result['module_config'] = {"required": required, |
| 338 |
"properties": properties, |
| 339 |
"validationAction": action, |
| 340 |
"validationLevel": level} |
| 341 |
|
| 342 |
module.exit_json(**result) |
| 343 |
|
| 344 |
|
| 345 |
if __name__ == '__main__': |
| 346 |
main() |