| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# (c) 2022, Rhys Campbell <[email protected]> |
| 4 |
|
| 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 = ''' |
| 12 |
--- |
| 13 |
module: mongodb_role |
| 14 |
short_description: Adds or removes a role from a MongoDB database |
| 15 |
description: |
| 16 |
- Adds or removes a role from a MongoDB database. |
| 17 |
- For further information on the required format for \ |
| 18 |
the privileges, authenticationRestriction or roles \ |
| 19 |
parameters, see the MongoDB Documentation https://www.mongodb.com/docs/manual/reference/command/createRole/ |
| 20 |
version_added: "1.5.0" |
| 21 |
|
| 22 |
extends_documentation_fragment: |
| 23 |
- community.mongodb.login_options |
| 24 |
- community.mongodb.ssl_options |
| 25 |
|
| 26 |
options: |
| 27 |
replica_set: |
| 28 |
description: |
| 29 |
- Replica set to connect to (automatically connects to primary for writes). |
| 30 |
type: str |
| 31 |
database: |
| 32 |
description: |
| 33 |
- The name of the database to add/remove the role from. |
| 34 |
required: true |
| 35 |
type: str |
| 36 |
aliases: [db] |
| 37 |
name: |
| 38 |
description: |
| 39 |
- The name of the role to add or remove. |
| 40 |
required: true |
| 41 |
aliases: [user] |
| 42 |
type: str |
| 43 |
privileges: |
| 44 |
type: list |
| 45 |
elements: raw |
| 46 |
description: |
| 47 |
- > |
| 48 |
The privileges to grant the role. A privilege consists of a resource |
| 49 |
and permitted actions. |
| 50 |
default: [] |
| 51 |
authenticationRestrictions: |
| 52 |
type: list |
| 53 |
elements: raw |
| 54 |
description: |
| 55 |
- > |
| 56 |
The authentication restrictions the server enforces on the role. |
| 57 |
Specifies a list of IP addresses and CIDR ranges users granted |
| 58 |
this role are allowed to connect to and/or which they can connect from. |
| 59 |
Provide a list of dictionaries with the following |
| 60 |
fields: clientSource (list), serverAddress (list). |
| 61 |
Provide an empty list if you don't want to use the field. |
| 62 |
default: [] |
| 63 |
roles: |
| 64 |
type: list |
| 65 |
elements: raw |
| 66 |
description: |
| 67 |
- > |
| 68 |
The database user roles should be provided as a dictionary with the db and role keys. |
| 69 |
default: [] |
| 70 |
state: |
| 71 |
description: |
| 72 |
- The database user state. |
| 73 |
default: present |
| 74 |
choices: [absent, present] |
| 75 |
type: str |
| 76 |
debug: |
| 77 |
description: |
| 78 |
- Enable extra debugging output. |
| 79 |
default: false |
| 80 |
type: bool |
| 81 |
notes: |
| 82 |
- Requires the pymongo Python package on the remote host, version 4+. This |
| 83 |
can be installed using pip or the OS package manager. Newer mongo server versions require newer |
| 84 |
pymongo versions. @see https://www.mongodb.com/docs/languages/python/pymongo-driver/current/compatibility/ |
| 85 |
requirements: |
| 86 |
- "pymongo" |
| 87 |
author: |
| 88 |
- "Rhys Campbell (@rhysmeister)" |
| 89 |
''' |
| 90 |
|
| 91 |
EXAMPLES = ''' |
| 92 |
- name: Create sales role |
| 93 |
community.mongodb.mongodb_role: |
| 94 |
name: sales |
| 95 |
database: salesdb |
| 96 |
privileges: |
| 97 |
- resource: |
| 98 |
db: salesdb |
| 99 |
collection: "" |
| 100 |
actions: |
| 101 |
- find |
| 102 |
state: present |
| 103 |
|
| 104 |
- name: Create ClusterAdmin Role |
| 105 |
community.mongodb.mongodb_role: |
| 106 |
name: myClusterwideAdmin |
| 107 |
database: admin |
| 108 |
privileges: |
| 109 |
- resource: |
| 110 |
cluster: true |
| 111 |
actions: |
| 112 |
- addShard |
| 113 |
- resource: |
| 114 |
db: config |
| 115 |
collection: "" |
| 116 |
actions: |
| 117 |
- find |
| 118 |
- update |
| 119 |
- insert |
| 120 |
- remove |
| 121 |
- resource: |
| 122 |
db: "users" |
| 123 |
collection: "usersCollection" |
| 124 |
actions: |
| 125 |
- update |
| 126 |
- insert |
| 127 |
- remove |
| 128 |
- resource: |
| 129 |
db: "" |
| 130 |
collection: "" |
| 131 |
actions: |
| 132 |
- find |
| 133 |
roles: |
| 134 |
- role: "read" |
| 135 |
db: "admin" |
| 136 |
state: present |
| 137 |
|
| 138 |
- name: Create ClusterAdmin Role with a login only from 127.0.0.1 restriction |
| 139 |
community.mongodb.mongodb_role: |
| 140 |
name: myClusterwideAdmin |
| 141 |
database: admin |
| 142 |
privileges: |
| 143 |
- resource: |
| 144 |
cluster: true |
| 145 |
actions: |
| 146 |
- addShard |
| 147 |
- resource: |
| 148 |
db: config |
| 149 |
collection: "" |
| 150 |
actions: |
| 151 |
- find |
| 152 |
- update |
| 153 |
- insert |
| 154 |
- resource: |
| 155 |
db: "users" |
| 156 |
collection: "usersCollection" |
| 157 |
actions: |
| 158 |
- update |
| 159 |
- insert |
| 160 |
- remove |
| 161 |
- resource: |
| 162 |
db: "" |
| 163 |
collection: "" |
| 164 |
actions: |
| 165 |
- find |
| 166 |
roles: |
| 167 |
- role: "read" |
| 168 |
db: "admin" |
| 169 |
- role: "read" |
| 170 |
db: "mynewdb" |
| 171 |
authenticationRestrictions: |
| 172 |
- clientSource: |
| 173 |
- "127.0.0.1" |
| 174 |
serverAddress: [] |
| 175 |
state: present |
| 176 |
|
| 177 |
- name: Delete sales role |
| 178 |
community.mongodb.mongodb_role: |
| 179 |
name: sales |
| 180 |
database: "salesdb" |
| 181 |
state: absent |
| 182 |
|
| 183 |
- name: Delete myClusterwideAdmin role |
| 184 |
community.mongodb.mongodb_role: |
| 185 |
name: myClusterwideAdmin |
| 186 |
database: admin |
| 187 |
state: absent |
| 188 |
''' |
| 189 |
|
| 190 |
RETURN = ''' |
| 191 |
user: |
| 192 |
description: The name of the role to add or remove. |
| 193 |
returned: success |
| 194 |
type: str |
| 195 |
''' |
| 196 |
|
| 197 |
import traceback |
| 198 |
|
| 199 |
|
| 200 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 201 |
from ansible.module_utils._text import to_native |
| 202 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 203 |
missing_required_lib, |
| 204 |
mongodb_common_argument_spec, |
| 205 |
mongo_auth, |
| 206 |
PYMONGO_IMP_ERR, |
| 207 |
pymongo_found, |
| 208 |
get_mongodb_client, |
| 209 |
) |
| 210 |
|
| 211 |
|
| 212 |
def role_find(client, role, db_name): |
| 213 |
"""Check if the role exists. |
| 214 |
|
| 215 |
Args: |
| 216 |
client (cursor): Mongodb cursor on admin database. |
| 217 |
user (str): Role to check. |
| 218 |
db_name (str): Role's database. |
| 219 |
|
| 220 |
Returns: |
| 221 |
dict: when role exists, False otherwise. |
| 222 |
""" |
| 223 |
try: |
| 224 |
mongo_role = None |
| 225 |
rolesDoc = { |
| 226 |
'rolesInfo': 1, |
| 227 |
'showAuthenticationRestrictions': True, |
| 228 |
'showPrivileges': True |
| 229 |
} |
| 230 |
for mongo_role in client[db_name].command(rolesDoc)['roles']: |
| 231 |
if mongo_role['role'] == role: |
| 232 |
# NOTE: there is no 'db' field in mongo 2.4. |
| 233 |
if 'db' not in mongo_role: |
| 234 |
return mongo_role |
| 235 |
# Workaround to make the condition works with AWS DocumentDB, |
| 236 |
# since all users are in the admin database. |
| 237 |
if mongo_role["db"] in [db_name, "admin"]: |
| 238 |
return mongo_role |
| 239 |
except Exception as excep: |
| 240 |
if hasattr(excep, 'code') and excep.code == 31: # 31=RoleNotFound |
| 241 |
pass # Allow return False |
| 242 |
else: |
| 243 |
raise |
| 244 |
return False |
| 245 |
|
| 246 |
|
| 247 |
def role_add(client, db_name, role, privileges, roles, authenticationRestrictions): |
| 248 |
db = client[db_name] |
| 249 |
|
| 250 |
try: |
| 251 |
exists = role_find(client, role, db_name) |
| 252 |
except Exception as excep: |
| 253 |
# probably not needed for role create... to clarify |
| 254 |
# We get this exception: "not authorized on admin to execute command" |
| 255 |
# when auth is enabled on a new instance. The localhost exception should |
| 256 |
# allow us to create the first user. If the localhost exception does not apply, |
| 257 |
# then user creation will also fail with unauthorized. So, ignore Unauthorized here. |
| 258 |
if hasattr(excep, 'code') and excep.code == 13: # 13=Unauthorized |
| 259 |
exists = False |
| 260 |
else: |
| 261 |
raise |
| 262 |
|
| 263 |
if exists: |
| 264 |
role_add_db_command = 'updateRole' |
| 265 |
else: |
| 266 |
role_add_db_command = 'createRole' |
| 267 |
|
| 268 |
role_dict = {} |
| 269 |
|
| 270 |
role_dict["privileges"] = privileges |
| 271 |
role_dict["roles"] = roles |
| 272 |
role_dict["authenticationRestrictions"] = authenticationRestrictions |
| 273 |
db.command(role_add_db_command, role, **role_dict) |
| 274 |
|
| 275 |
|
| 276 |
def role_remove(module, client, db_name, role): |
| 277 |
exists = role_find(client, role, db_name) |
| 278 |
if exists: |
| 279 |
if module.check_mode: |
| 280 |
module.exit_json(changed=True, role=role) |
| 281 |
db = client[db_name] |
| 282 |
db.command("dropRole", role) |
| 283 |
else: |
| 284 |
module.exit_json(changed=False, role=role) |
| 285 |
|
| 286 |
|
| 287 |
def check_if_role_changed(client, role, db_name, privileges, authenticationRestrictions, roles): |
| 288 |
role_dict = role_find(client, role, db_name) |
| 289 |
changed = False |
| 290 |
if role_dict: |
| 291 |
reformat_authenticationRestrictions = [] |
| 292 |
if 'authenticationRestrictions' in role_dict: |
| 293 |
for item in role_dict['authenticationRestrictions']: |
| 294 |
reformat_authenticationRestrictions.append(item[0]) # seems to be a list of lists of dict, we want a list of dicts |
| 295 |
if ('privileges' in role_dict and |
| 296 |
[{'resource': d['resource'], 'actions': sorted(d['actions'])} for d in role_dict['privileges']] != |
| 297 |
[{'resource': d['resource'], 'actions': sorted(d['actions'])} for d in privileges] or |
| 298 |
'privileges' not in role_dict and privileges != []): |
| 299 |
changed = True |
| 300 |
elif ('roles' in role_dict and |
| 301 |
sorted(role_dict['roles'], key=lambda x: (x["db"], x["role"])) != |
| 302 |
sorted(roles, key=lambda x: (x["db"], x["role"])) or |
| 303 |
'roles' not in role_dict and roles != []): |
| 304 |
changed = True |
| 305 |
elif ('authenticationRestrictions' in role_dict and |
| 306 |
sorted(reformat_authenticationRestrictions, key=lambda x: (x.get('clientSource', ''), x.get('serverAddress', ''))) != |
| 307 |
sorted(authenticationRestrictions, key=lambda x: (x.get('clientSource', ''), x.get('serverAddress', ''))) or |
| 308 |
'authenticationRestrictions' not in role_dict and authenticationRestrictions != []): |
| 309 |
changed = True |
| 310 |
else: |
| 311 |
raise Exception("Role not found") # TODO replace with proper exception |
| 312 |
return changed |
| 313 |
|
| 314 |
|
| 315 |
# ========================================= |
| 316 |
# Module execution. |
| 317 |
# |
| 318 |
|
| 319 |
def main(): |
| 320 |
argument_spec = mongodb_common_argument_spec() |
| 321 |
argument_spec.update( |
| 322 |
replica_set=dict(default=None), |
| 323 |
database=dict(required=True, aliases=['db']), |
| 324 |
name=dict(required=True, aliases=['user']), |
| 325 |
privileges=dict(default=[], type='list', elements='raw'), |
| 326 |
authenticationRestrictions=dict(default=[], type='list', elements='raw'), |
| 327 |
roles=dict(default=[], type='list', elements='raw'), |
| 328 |
state=dict(default='present', choices=['absent', 'present']), |
| 329 |
debug=dict(type='bool', default=False), |
| 330 |
) |
| 331 |
module = AnsibleModule( |
| 332 |
argument_spec=argument_spec, |
| 333 |
supports_check_mode=True, |
| 334 |
) |
| 335 |
|
| 336 |
if not pymongo_found: |
| 337 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 338 |
exception=PYMONGO_IMP_ERR) |
| 339 |
|
| 340 |
try: |
| 341 |
directConnection = False |
| 342 |
if module.params['replica_set'] is None: |
| 343 |
directConnection = True |
| 344 |
client = get_mongodb_client(module, directConnection=directConnection) |
| 345 |
client = mongo_auth(module, client, directConnection=directConnection) |
| 346 |
except Exception as e: |
| 347 |
module.fail_json(msg='Unable to connect to database: %s' % to_native(e)) |
| 348 |
|
| 349 |
changed = None |
| 350 |
role = state = module.params['name'] |
| 351 |
state = module.params['state'] |
| 352 |
db_name = module.params['database'] |
| 353 |
privileges = module.params['privileges'] |
| 354 |
roles = module.params['roles'] |
| 355 |
authenticationRestrictions = module.params['authenticationRestrictions'] |
| 356 |
debug = module.params['debug'] |
| 357 |
# TODO _ Functions use a different param order... make consistent |
| 358 |
try: |
| 359 |
if state == 'present': |
| 360 |
if role_find(client, role, db_name) is False: |
| 361 |
if module.check_mode is False: |
| 362 |
role_add(client, db_name, role, privileges, roles, authenticationRestrictions) |
| 363 |
changed = True |
| 364 |
else: |
| 365 |
if check_if_role_changed(client, role, db_name, privileges, authenticationRestrictions, roles): |
| 366 |
if module.check_mode is False: |
| 367 |
role_add(client, db_name, role, privileges, roles, authenticationRestrictions) |
| 368 |
changed = True |
| 369 |
else: |
| 370 |
changed = False |
| 371 |
elif state == 'absent': |
| 372 |
if role_find(client, role, db_name): |
| 373 |
if module.check_mode is False: |
| 374 |
role_remove(module, client, db_name, role) |
| 375 |
changed = True |
| 376 |
else: |
| 377 |
changed = False |
| 378 |
module.exit_json(changed=changed, role=role) |
| 379 |
except Exception as e: |
| 380 |
if debug: |
| 381 |
module.fail_json(msg=str(e), traceback=traceback.format_exc()) |
| 382 |
else: |
| 383 |
module.fail_json(msg=str(e)) |
| 384 |
|
| 385 |
|
| 386 |
if __name__ == '__main__': |
| 387 |
main() |