| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2020, Andrew Klychkov (@Andersson007) <[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_info |
| 14 |
|
| 15 |
short_description: Gather information about MongoDB instance. |
| 16 |
|
| 17 |
description: |
| 18 |
- Gather information about MongoDB instance. |
| 19 |
|
| 20 |
author: Andrew Klychkov (@Andersson007) |
| 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 |
filter: |
| 29 |
description: |
| 30 |
- Limit the collected information by comma separated string or YAML list. |
| 31 |
- Allowable values are C(general), C(databases), C(total_size), C(parameters), C(users), C(roles). |
| 32 |
- By default, collects all subsets. |
| 33 |
- You can use '!' before value (for example, C(!users)) to exclude it from the information. |
| 34 |
- If you pass including and excluding values to the filter, for example, I(filter=!general,users), |
| 35 |
the excluding values, C(!general) in this case, will be ignored. |
| 36 |
required: no |
| 37 |
type: list |
| 38 |
elements: str |
| 39 |
|
| 40 |
notes: |
| 41 |
- Requires the pymongo Python package on the remote host, version 4+. |
| 42 |
|
| 43 |
requirements: |
| 44 |
- pymongo |
| 45 |
''' |
| 46 |
|
| 47 |
EXAMPLES = r''' |
| 48 |
- name: Gather all supported information |
| 49 |
community.mongodb.mongodb_info: |
| 50 |
login_user: admin |
| 51 |
login_password: secret |
| 52 |
register: result |
| 53 |
|
| 54 |
- name: Show gathered info |
| 55 |
debug: |
| 56 |
msg: '{{ result }}' |
| 57 |
|
| 58 |
- name: Gather only information about databases and their total size |
| 59 |
community.mongodb.mongodb_info: |
| 60 |
login_user: admin |
| 61 |
login_password: secret |
| 62 |
filter: databases, total_size |
| 63 |
|
| 64 |
- name: Gather all information except parameters |
| 65 |
community.mongodb.mongodb_info: |
| 66 |
login_user: admin |
| 67 |
login_password: secret |
| 68 |
filter: '!parameters' |
| 69 |
''' |
| 70 |
|
| 71 |
RETURN = r''' |
| 72 |
general: |
| 73 |
description: General instance information. |
| 74 |
returned: always |
| 75 |
type: dict |
| 76 |
sample: {"allocator": "tcmalloc", "bits": 64, "storageEngines": ["biggie"], "version": "4.2.3", "maxBsonObjectSize": 16777216} |
| 77 |
databases: |
| 78 |
description: Database information. |
| 79 |
returned: always |
| 80 |
type: dict |
| 81 |
sample: {"admin": {"empty": false, "sizeOnDisk": 245760}, "config": {"empty": false, "sizeOnDisk": 110592}} |
| 82 |
total_size: |
| 83 |
description: Total size of all databases in bytes. |
| 84 |
returned: always |
| 85 |
type: int |
| 86 |
sample: 397312 |
| 87 |
users: |
| 88 |
description: User information. |
| 89 |
returned: always |
| 90 |
type: dict |
| 91 |
sample: { "db": {"new_user": {"_id": "config.new_user", "mechanisms": ["SCRAM-SHA-1", "SCRAM-SHA-256"], "roles": []}}} |
| 92 |
roles: |
| 93 |
description: Role information. |
| 94 |
returned: always |
| 95 |
type: dict |
| 96 |
sample: { "db": {"restore": {"inheritedRoles": [], "isBuiltin": true, "roles": []}}} |
| 97 |
parameters: |
| 98 |
description: Server parameters information. |
| 99 |
returned: always |
| 100 |
type: dict |
| 101 |
sample: {"maxOplogTruncationPointsAfterStartup": 100, "maxOplogTruncationPointsDuringStartup": 100, "maxSessions": 1000000} |
| 102 |
''' |
| 103 |
|
| 104 |
from uuid import UUID |
| 105 |
|
| 106 |
from ansible.module_utils.basic import AnsibleModule |
| 107 |
from ansible.module_utils._text import to_native |
| 108 |
from ansible.module_utils.six import iteritems # pylint: disable=ansible-bad-import-from |
| 109 |
from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import ( |
| 110 |
convert_bson_values_recur, |
| 111 |
get_mongodb_client, |
| 112 |
missing_required_lib, |
| 113 |
mongodb_common_argument_spec, |
| 114 |
mongo_auth, |
| 115 |
PYMONGO_IMP_ERR, |
| 116 |
pymongo_found, |
| 117 |
) |
| 118 |
|
| 119 |
|
| 120 |
class MongoDbInfo(): |
| 121 |
"""Class for gathering MongoDB instance information. |
| 122 |
|
| 123 |
Args: |
| 124 |
module (AnsibleModule): Object of AnsibleModule class. |
| 125 |
client (pymongo): pymongo client object to interact with the database. |
| 126 |
""" |
| 127 |
def __init__(self, module, client): |
| 128 |
self.module = module |
| 129 |
self.client = client |
| 130 |
self.admin_db = self.client.admin |
| 131 |
self.info = { |
| 132 |
'general': {}, |
| 133 |
'databases': {}, |
| 134 |
'total_size': {}, |
| 135 |
'parameters': {}, |
| 136 |
'users': {}, |
| 137 |
'roles': {}, |
| 138 |
} |
| 139 |
|
| 140 |
def get_info(self, filter_): |
| 141 |
"""Get MongoDB instance information and return it based on filter_. |
| 142 |
|
| 143 |
Args: |
| 144 |
filter_ (list): List of collected subsets (e.g., general, users, etc.), |
| 145 |
when it is empty, return all available information. |
| 146 |
""" |
| 147 |
self.__collect() |
| 148 |
|
| 149 |
inc_list = [] |
| 150 |
exc_list = [] |
| 151 |
|
| 152 |
if filter_: |
| 153 |
partial_info = {} |
| 154 |
|
| 155 |
for fi in filter_: |
| 156 |
if fi.lstrip('!') not in self.info: |
| 157 |
self.module.warn("filter element '%s' is not allowable, ignored" % fi) |
| 158 |
continue |
| 159 |
|
| 160 |
if fi[0] == '!': |
| 161 |
exc_list.append(fi.lstrip('!')) |
| 162 |
|
| 163 |
else: |
| 164 |
inc_list.append(fi) |
| 165 |
|
| 166 |
if inc_list: |
| 167 |
for i in self.info: |
| 168 |
if i in inc_list: |
| 169 |
partial_info[i] = self.info[i] |
| 170 |
|
| 171 |
else: |
| 172 |
for i in self.info: |
| 173 |
if i not in exc_list: |
| 174 |
partial_info[i] = self.info[i] |
| 175 |
|
| 176 |
return partial_info |
| 177 |
|
| 178 |
else: |
| 179 |
return self.info |
| 180 |
|
| 181 |
def __collect(self): |
| 182 |
"""Collect information.""" |
| 183 |
# Get general info: |
| 184 |
self.info['general'] = self.client.server_info() |
| 185 |
|
| 186 |
# Get parameters: |
| 187 |
self.info['parameters'] = self.get_parameters_info() |
| 188 |
|
| 189 |
# Gather info about databases and their total size: |
| 190 |
self.info['databases'], self.info['total_size'] = self.get_db_info() |
| 191 |
|
| 192 |
for dbname, val in iteritems(self.info['databases']): |
| 193 |
# Gather info about users for each database: |
| 194 |
self.info['users'].update(self.get_users_info(dbname)) |
| 195 |
|
| 196 |
# Gather info about roles for each database: |
| 197 |
self.info['roles'].update(self.get_roles_info(dbname)) |
| 198 |
|
| 199 |
self.info = convert_bson_values_recur(self.info) |
| 200 |
|
| 201 |
def get_roles_info(self, dbname): |
| 202 |
"""Gather information about roles. |
| 203 |
|
| 204 |
Args: |
| 205 |
dbname (str): Database name to get role info from. |
| 206 |
|
| 207 |
Returns a dictionary with role information for the given db. |
| 208 |
""" |
| 209 |
db = self.client[dbname] |
| 210 |
result = db.command({'rolesInfo': 1, 'showBuiltinRoles': True})['roles'] |
| 211 |
|
| 212 |
roles_dict = {} |
| 213 |
for elem in result: |
| 214 |
roles_dict[elem['role']] = {} |
| 215 |
for key, val in iteritems(elem): |
| 216 |
if key in ['role', 'db']: |
| 217 |
continue |
| 218 |
|
| 219 |
roles_dict[elem['role']][key] = val |
| 220 |
|
| 221 |
return {dbname: roles_dict} |
| 222 |
|
| 223 |
def get_users_info(self, dbname): |
| 224 |
"""Gather information about users. |
| 225 |
|
| 226 |
Args: |
| 227 |
dbname (str): Database name to get user info from. |
| 228 |
|
| 229 |
Returns a dictionary with user information for the given db. |
| 230 |
""" |
| 231 |
db = self.client[dbname] |
| 232 |
result = db.command({'usersInfo': 1})['users'] |
| 233 |
|
| 234 |
users_dict = {} |
| 235 |
for elem in result: |
| 236 |
users_dict[elem['user']] = {} |
| 237 |
for key, val in iteritems(elem): |
| 238 |
if key in ['user', 'db']: |
| 239 |
continue |
| 240 |
|
| 241 |
if isinstance(val, UUID): |
| 242 |
val = val.hex |
| 243 |
|
| 244 |
users_dict[elem['user']][key] = str(val) # Force conversion to avoid: Refusing to deserialize an invalid UTF8 string value |
| 245 |
|
| 246 |
return {dbname: users_dict} |
| 247 |
|
| 248 |
def get_db_info(self): |
| 249 |
"""Gather information about databases. |
| 250 |
|
| 251 |
Returns a dictionary with database information. |
| 252 |
""" |
| 253 |
result = self.admin_db.command({'listDatabases': 1}) |
| 254 |
total_size = int(result['totalSize']) |
| 255 |
result = result['databases'] |
| 256 |
|
| 257 |
db_dict = {} |
| 258 |
for elem in result: |
| 259 |
db_dict[elem['name']] = {} |
| 260 |
for key, val in iteritems(elem): |
| 261 |
if key == 'name': |
| 262 |
continue |
| 263 |
|
| 264 |
if key == 'sizeOnDisk': |
| 265 |
val = int(val) |
| 266 |
|
| 267 |
db_dict[elem['name']][key] = val |
| 268 |
|
| 269 |
return db_dict, total_size |
| 270 |
|
| 271 |
def get_parameters_info(self): |
| 272 |
"""Gather parameters information. |
| 273 |
|
| 274 |
Returns a dictionary with parameters. |
| 275 |
""" |
| 276 |
return self.admin_db.command({'getParameter': '*'}) |
| 277 |
|
| 278 |
|
| 279 |
# ================ |
| 280 |
# Module execution |
| 281 |
# |
| 282 |
def main(): |
| 283 |
argument_spec = mongodb_common_argument_spec() |
| 284 |
argument_spec.update( |
| 285 |
filter=dict(type='list', elements='str', required=False) |
| 286 |
) |
| 287 |
module = AnsibleModule( |
| 288 |
argument_spec=argument_spec, |
| 289 |
supports_check_mode=True, |
| 290 |
required_together=[['login_user', 'login_password']], |
| 291 |
) |
| 292 |
|
| 293 |
if not pymongo_found: |
| 294 |
module.fail_json(msg=missing_required_lib('pymongo'), |
| 295 |
exception=PYMONGO_IMP_ERR) |
| 296 |
|
| 297 |
filter_ = module.params['filter'] |
| 298 |
|
| 299 |
if filter_: |
| 300 |
filter_ = [f.strip() for f in filter_] |
| 301 |
|
| 302 |
try: |
| 303 |
client = get_mongodb_client(module) |
| 304 |
client = mongo_auth(module, client) |
| 305 |
except Exception as excep: |
| 306 |
module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep)) |
| 307 |
|
| 308 |
# Initialize an object and start main work: |
| 309 |
mongodb = MongoDbInfo(module, client) |
| 310 |
|
| 311 |
module.exit_json(changed=False, **mongodb.get_info(filter_)) |
| 312 |
|
| 313 |
|
| 314 |
if __name__ == '__main__': |
| 315 |
main() |