Debian Codegraph @

ansible_collections/community/mongodb/plugins/modules/mongodb_shell.py

raw
1 #!/usr/bin/python
2
3 # 2020 Rhys Campbell <[email protected]>
4 # https://github.com/rhysmeister
5 # GNU General Public License v3.0+
6 # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7 from __future__ import absolute_import, division, print_function
8
9
10 DOCUMENTATION = '''
11 ---
12 module: mongodb_shell
13 author: Rhys Campbell (@rhysmeister)
14 version_added: "1.1.0"
15 short_description: Run commands via the MongoDB shell.
16 requirements:
17 - mongosh
18 description:
19 - Run commands via the MongoDB shell.
20 - Commands provided with the eval parameter or included in a Javascript file.
21 - Attempts to parse returned data into a format that Ansible can use.
22 - Module uses the mongosh shell by default.
23 - Support for mongo is depreciated.
24
25 extends_documentation_fragment:
26 - community.mongodb.login_options
27 - community.mongodb.ssl_options
28
29 options:
30 mongo_cmd:
31 description:
32 - The MongoDB shell command.
33 - auto - Automatically detect which MongoDB shell command used. Use "mongosh" if available, else use "mongo" command.
34 - mongo - This should still work for most cases but you might have problems with json parsinf. Use transform_type of 'raw' is you encounter problems.
35 type: str
36 default: "mongosh"
37 db:
38 description:
39 - The database to run commands against
40 type: str
41 required: false
42 default: "test"
43 file:
44 description:
45 - Path to a file containing MongoDB commands.
46 type: str
47 eval:
48 description:
49 - A MongoDB command to run.
50 type: str
51 nodb:
52 description:
53 - Specify a non-default encoding for output.
54 type: bool
55 default: false
56 norc:
57 description:
58 - Prevents the shell from sourcing and evaluating ~/.mongorc.js on start up.
59 type: bool
60 default: false
61 quiet:
62 description:
63 - Silences output from the shell during the connection process..
64 type: bool
65 default: true
66 debug:
67 description:
68 - show additional debug info.
69 type: bool
70 default: false
71 transform:
72 description:
73 - Transform the output returned to the user.
74 - auto - Attempt to automatically decide the best tranformation.
75 - split - Split output on a character.
76 - json - parse as json.
77 - raw - Return the raw output.
78 type: str
79 choices:
80 - "auto"
81 - "split"
82 - "json"
83 - "raw"
84 default: "auto"
85 split_char:
86 description:
87 - Used by the split action in the transform stage.
88 type: str
89 default: " "
90 stringify:
91 description:
92 - Wraps the command in eval in JSON.stringify(<js cmd>) (mongo) or EJSON.stringify(<js cmd>) (mongosh).
93 - Useful for escaping documents that are returned in Extended JSON format.
94 - Automatically set to false when using mongo.
95 - Automatically set to true when using mongosh.
96 - Set explicitly to override automatic selection.
97 type: bool
98 default: null
99 additional_args:
100 description:
101 - Additional arguments to supply to the mongo command.
102 - Supply as key-value pairs.
103 - If the parameter is a valueless flag supply an empty string as the value.
104 type: raw
105 idempotent:
106 description:
107 - Provides a form of pseudo-idempotency to the module.
108 - We perform a hash calculation on the contents of the eval key or the file name provided in the file key.
109 - When the command is first execute a filed called <hash>.success will be created.
110 - The module will not rerun the command if this file exists and idempotent is set to true.
111 type: bool
112 default: false
113 omit:
114 description:
115 - Parameter to omit from the command line.
116 - This should match the parameter name that the MongoDB shell accepts not the module name.
117 type: list
118 elements: str
119 default: []
120 '''
121
122 EXAMPLES = '''
123 - name: Run the listDatabases command
124 community.mongodb.mongodb_shell:
125 login_user: user
126 login_password: secret
127 eval: "db.adminCommand('listDatabases')"
128
129 - name: List collections and stringify the output
130 community.mongodb.mongodb_shell:
131 login_user: user
132 login_password: secret
133 eval: "db.adminCommand('listCollections')"
134 stringify: yes
135
136 - name: Run the showBuiltinRoles command
137 community.mongodb.mongodb_shell:
138 login_user: user
139 login_password: secret
140 eval: "db.getRoles({showBuiltinRoles: true})"
141
142 - name: Run a js file containing MongoDB commands with pseudo-idempotency
143 community.mongodb.mongodb_shell:
144 login_user: user
145 login_password: secret
146 file: "/path/to/mongo/file.js"
147 idempotent: yes
148
149 - name: Provide a couple of additional cmd args
150 community.mongodb.mongodb_shell:
151 login_user: user
152 login_password: secret
153 eval: "db.adminCommand('listDatabases')"
154 additional_args:
155 verbose: True
156 networkMessageCompressors: "snappy"
157 '''
158
159 RETURN = '''
160 file:
161 description: JS file that was executed successfully.
162 returned: When a js file is used.
163 type: str
164 msg:
165 description: A message indicating what has happened.
166 returned: always
167 type: str
168 transformed_output:
169 description: Output from the mongo command. We attempt to parse this into a list or json where possible.
170 returned: on success
171 type: list
172 changed:
173 description: Change status.
174 returned: always
175 type: bool
176 failed:
177 description: Something went wrong.
178 returned: on failure
179 type: bool
180 out:
181 description: Raw stdout from mongo.
182 returned: when debug is set to true
183 type: str
184 err:
185 description: Raw stderr from mongo.
186 returned: when debug is set to true
187 type: str
188 rc:
189 description: Return code from mongo.
190 returned: when debug is set to true
191 type: int
192 '''
193
194 from ansible.module_utils.basic import AnsibleModule
195 import os
196 __metaclass__ = type
197
198 from ansible_collections.community.mongodb.plugins.module_utils.mongodb_common import (
199 load_mongocnf, mongodb_common_argument_spec
200 )
201
202 from ansible_collections.community.mongodb.plugins.module_utils.mongodb_shell import (
203 add_arg_to_cmd,
204 transform_output,
205 get_hash_value,
206 touch,
207 detect_if_cmd_exist
208 )
209
210
211 def main():
212 argument_spec = mongodb_common_argument_spec(ssl_options=True)
213 argument_spec.update(
214 mongo_cmd=dict(type='str', default="mongosh"),
215 file=dict(type='str', required=False),
216 eval=dict(type='str', required=False),
217 db=dict(type='str', required=False, default="test"),
218 nodb=dict(type='bool', required=False, default=False),
219 norc=dict(type='bool', required=False, default=False),
220 quiet=dict(type='bool', required=False, default=True),
221 debug=dict(type='bool', required=False, default=False),
222 transform=dict(type='str', choices=["auto", "split", "json", "raw"], default="auto"),
223 split_char=dict(type='str', default=" "),
224 stringify=dict(type='bool', default=None),
225 additional_args=dict(type='raw'),
226 idempotent=dict(type='bool', default=False),
227 omit=dict(type='list', elements='str', default=[]),
228 )
229 module = AnsibleModule(
230 argument_spec=argument_spec,
231 supports_check_mode=False,
232 required_together=[['login_user', 'login_password']],
233 mutually_exclusive=[["eval", "file"]]
234 )
235
236 if module.params['mongo_cmd'] == "auto":
237 module.params['mongo_cmd'] = "mongosh" if detect_if_cmd_exist() else "mongo"
238
239 if module.params['mongo_cmd'] == "mongo" and module.params['stringify'] is None:
240 module.params['stringify'] = False
241 elif module.params['mongo_cmd'] == "mongosh" and module.params['stringify'] is None:
242 module.params['stringify'] = True
243
244 args = [
245 module.params['mongo_cmd'],
246 module.params['db']
247 ]
248
249 hash_value = get_hash_value(module)
250
251 if module.params['idempotent']:
252 if os.path.isfile("{0}.success".format(hash_value)):
253 module.exit_json(changed=False,
254 msg="The file {0}.success was found meaning this "
255 "command has already successfully executed "
256 "on this MongoDB host.".format(hash_value))
257
258 if not module.params['file']:
259 if module.params['eval'].startswith("show "):
260 msg = "You cannot use any shell helper (e.g. use <dbname>, show dbs, etc.)"\
261 " inside the eval parameter because they are not valid JavaScript."
262 module.fail_json(msg=msg)
263 if module.params['stringify']:
264 if module.params['mongo_cmd'] != "mongosh":
265 module.params['eval'] = "JSON.stringify({0})".format(module.params['eval'])
266 else:
267 module.params['eval'] = "EJSON.stringify({0})".format(module.params['eval'])
268
269 omit = module.params['omit']
270
271 username = module.params['login_user']
272 password = module.params['login_password']
273
274 credentials = load_mongocnf()
275 if credentials:
276 if not username:
277 username = credentials['user']
278 if not password:
279 password = credentials['password']
280
281 tmp_con_options = ""
282 # TODO This could be refactored into a function
283 if module.params['connection_options']:
284 tmp_con_options = "?"
285 for item in module.params['connection_options']:
286 # could be a list of dicts or a list of strings
287 if isinstance(item, dict):
288 for key, value in item.items():
289 tmp_con_options += "{0}={1}&".format(key, value)
290 elif isinstance(item, str) and "=" in item:
291 tmp_con_options += "{0}&".format(item)
292 else:
293 raise ValueError("Invalid value supplied in connection_options: {0} .".format(str(item)))
294 # We need to use a different connection format when conn params are supplied
295 tmp_db = args[1]
296 tmp_con_options = tmp_con_options[:-1]
297 args[1] = "mongodb://{0}:{1}/{2}{3}".format(module.params['login_host'],
298 module.params['login_port'],
299 tmp_db,
300 tmp_con_options)
301 else:
302 args = add_arg_to_cmd(args, "--host", module.params['login_host'], omit=omit)
303 args = add_arg_to_cmd(args, "--port", module.params['login_port'], omit=omit)
304 args = add_arg_to_cmd(args, "--username", username, omit=omit)
305 args = add_arg_to_cmd(args, "--password", password, omit=omit)
306 args = add_arg_to_cmd(args, "--authenticationDatabase", module.params['login_database'], omit=omit)
307 args = add_arg_to_cmd(args, "--authenticationMechanism", module.params['auth_mechanism'], omit=omit)
308 args = add_arg_to_cmd(args, "--eval", module.params['eval'], omit=omit)
309 args = add_arg_to_cmd(args, "--nodb", None, module.params['nodb'], omit=omit)
310 args = add_arg_to_cmd(args, "--norc", None, module.params['norc'], omit=omit)
311 args = add_arg_to_cmd(args, "--quiet", None, module.params['quiet'], omit=omit)
312
313 args = add_arg_to_cmd(args, "--tls", None, module.params['ssl'], omit=omit)
314 args = add_arg_to_cmd(args, "--tlsAllowInvalidCertificates", None, module.params['ssl_cert_reqs'] in ('CERT_NONE', 'CERT_OPTIONAL'), omit=omit)
315 args = add_arg_to_cmd(args, "--tlsCAFile", module.params['ssl_ca_certs'], omit=omit)
316 args = add_arg_to_cmd(args, "--tlsCRLFile", module.params['ssl_crlfile'], omit=omit)
317 args = add_arg_to_cmd(args, "--tlsCertificateKeyFile", module.params['ssl_keyfile'], omit=omit)
318 args = add_arg_to_cmd(args, "--tlsCertificateKeyFilePassword", module.params['ssl_pem_passphrase'], omit=omit)
319
320 additional_args = module.params['additional_args']
321 if additional_args is not None:
322 for key, value in additional_args.items():
323 if isinstance(value, bool):
324 args.append(" --{0}".format(key))
325 elif isinstance(value, str) or isinstance(value, int):
326 args.append(" --{0} {1}".format(key, value))
327 if module.params['file']:
328 args.append(module.params['file'])
329
330 rc = None
331 out = ''
332 err = ''
333 result = {}
334 cmd = " ".join(str(item) for item in args)
335
336 # Change froma tuple to a dict - we want this to work across versions
337 run_rc = module.run_command(cmd, check_rc=False)
338 # Handle both tuple and dict styles
339 if isinstance(run_rc, tuple):
340 rc, out, err = run_rc
341 else:
342 rc = run_rc.get('rc')
343 out = run_rc.get('stdout', '')
344 err = run_rc.get('stderr', '')
345
346 if module.params['debug']:
347 result['out'] = out
348 result['err'] = err
349 result['rc'] = rc
350 result['cmd'] = cmd
351
352 if rc != 0:
353 if err is None or err == "":
354 err = out
355 module.fail_json(msg=err.strip(), **result)
356 else:
357 result['changed'] = True
358 if module.params['idempotent']:
359 touch("{0}.success".format(hash_value))
360 try:
361 output = transform_output(out,
362 module.params['transform'],
363 module.params['split_char'])
364 result['transformed_output'] = output
365 result['msg'] = "transform type was {0}".format(module.params['transform'])
366 if module.params['file'] is not None:
367 result['file'] = module.params['file']
368 except Exception as excep:
369 result['msg'] = "Error tranforming output: {0}".format(str(excep))
370 result['transformed_output'] = None
371
372 module.exit_json(**result)
373
374
375 if __name__ == '__main__':
376 main()