Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_console.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_system_console
23 short_description: Configure console in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify system feature and console category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 system_console:
80 description:
81 - Configure console.
82 default: null
83 type: dict
84 suboptions:
85 baudrate:
86 description:
87 - Console baud rate.
88 type: str
89 choices:
90 - '9600'
91 - '19200'
92 - '38400'
93 - '57600'
94 - '115200'
95 fortiexplorer:
96 description:
97 - Enable/disable access for FortiExplorer.
98 type: str
99 choices:
100 - 'enable'
101 - 'disable'
102 login:
103 description:
104 - Enable/disable serial console and FortiExplorer.
105 type: str
106 choices:
107 - 'enable'
108 - 'disable'
109 mode:
110 description:
111 - Console mode.
112 type: str
113 choices:
114 - 'batch'
115 - 'line'
116 output:
117 description:
118 - Console output mode.
119 type: str
120 choices:
121 - 'standard'
122 - 'more'
123 """
124
125 EXAMPLES = """
126 - name: Configure console.
127 fortinet.fortios.fortios_system_console:
128 vdom: "{{ vdom }}"
129 system_console:
130 baudrate: "9600"
131 fortiexplorer: "enable"
132 login: "enable"
133 mode: "batch"
134 output: "standard"
135 """
136
137 RETURN = """
138 build:
139 description: Build number of the fortigate image
140 returned: always
141 type: str
142 sample: '1547'
143 http_method:
144 description: Last method used to provision the content into FortiGate
145 returned: always
146 type: str
147 sample: 'PUT'
148 http_status:
149 description: Last result given by FortiGate on last operation applied
150 returned: always
151 type: str
152 sample: "200"
153 mkey:
154 description: Master key (id) used in the last call to FortiGate
155 returned: success
156 type: str
157 sample: "id"
158 name:
159 description: Name of the table used to fulfill the request
160 returned: always
161 type: str
162 sample: "urlfilter"
163 path:
164 description: Path of the table used to fulfill the request
165 returned: always
166 type: str
167 sample: "webfilter"
168 revision:
169 description: Internal revision number
170 returned: always
171 type: str
172 sample: "17.0.2.10658"
173 serial:
174 description: Serial number of the unit
175 returned: always
176 type: str
177 sample: "FGVMEVYYQT3AB5352"
178 status:
179 description: Indication of the operation's result
180 returned: always
181 type: str
182 sample: "success"
183 vdom:
184 description: Virtual domain used
185 returned: always
186 type: str
187 sample: "root"
188 version:
189 description: Version of the FortiGate
190 returned: always
191 type: str
192 sample: "v5.6.3"
193 """
194 from ansible.module_utils.basic import AnsibleModule
195 from ansible.module_utils.connection import Connection
196 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
197 FortiOSHandler,
198 )
199 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
200 check_legacy_fortiosapi,
201 )
202 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
203 schema_to_module_spec,
204 )
205 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
206 check_schema_versioning,
207 )
208 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
209 FAIL_SOCKET_MSG,
210 )
211 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
212 remove_invalid_fields,
213 )
214 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
215 is_same_comparison,
216 )
217 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
218 serialize,
219 )
220 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
221 find_current_values,
222 )
223 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
224 unify_data_format,
225 )
226
227
228 def filter_system_console_data(json):
229 option_list = ["baudrate", "fortiexplorer", "login", "mode", "output"]
230
231 json = remove_invalid_fields(json)
232 dictionary = {}
233
234 for attribute in option_list:
235 if attribute in json and json[attribute] is not None:
236 dictionary[attribute] = json[attribute]
237
238 return dictionary
239
240
241 def underscore_to_hyphen(data):
242 new_data = None
243 if isinstance(data, list):
244 new_data = []
245 for i, elem in enumerate(data):
246 new_data.append(underscore_to_hyphen(elem))
247 elif isinstance(data, dict):
248 new_data = {}
249 for k, v in data.items():
250 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
251 else:
252 return data
253 return new_data
254
255
256 def system_console(data, fos, check_mode=False):
257
258 state = None
259 vdom = data["vdom"]
260 parameters = None
261 state = data.get("state", None)
262 system_console_data = data["system_console"]
263
264 filtered_data = filter_system_console_data(system_console_data)
265 converted_data = underscore_to_hyphen(filtered_data)
266
267 # check_mode starts from here
268 if check_mode:
269 diff = {
270 "before": "",
271 "after": filtered_data,
272 }
273 mkeyname = fos.get_mkeyname(None, None)
274 mkey = fos.get_mkey("system", "console", filtered_data, vdom=vdom)
275 current_data = fos.get(
276 "system", "console", vdom=vdom, mkey=mkey, parameters=parameters
277 )
278 is_existed = (
279 current_data
280 and current_data.get("http_status") == 200
281 and (
282 mkeyname
283 and isinstance(current_data.get("results"), list)
284 and len(current_data["results"]) > 0
285 or not mkeyname
286 and current_data["results"] # global object response
287 )
288 )
289
290 # 2. if it exists and the state is 'present' then compare current settings with desired
291 if state == "present" or state is True or state is None:
292 # for non global modules, mkeyname must exist and it's a new module when mkey is None
293 if mkeyname is not None and mkey is None:
294 return False, True, filtered_data, diff
295
296 # if mkey exists then compare each other
297 # record exits and they're matched or not
298 copied_filtered_data = filtered_data.copy()
299 copied_filtered_data.pop(mkeyname, None)
300 unified_filtered_data = unify_data_format(copied_filtered_data)
301
302 current_data_results = current_data.get("results", {})
303 current_config = (
304 current_data_results[0]
305 if mkeyname
306 and isinstance(current_data_results, list)
307 and len(current_data_results) > 0
308 else current_data_results
309 )
310 if is_existed:
311 unified_current_values = find_current_values(
312 unified_filtered_data,
313 unify_data_format(current_config),
314 )
315
316 is_same = is_same_comparison(
317 serialize(unified_current_values), serialize(unified_filtered_data)
318 )
319
320 return (
321 False,
322 not is_same,
323 filtered_data,
324 {"before": unified_current_values, "after": unified_filtered_data},
325 )
326
327 # record does not exist
328 return False, True, filtered_data, diff
329
330 if state == "absent":
331 if mkey is None:
332 return (
333 False,
334 False,
335 filtered_data,
336 {"before": current_data["results"][0], "after": ""},
337 )
338
339 if is_existed:
340 return (
341 False,
342 True,
343 filtered_data,
344 {"before": current_data["results"][0], "after": ""},
345 )
346 return False, False, filtered_data, {}
347
348 return True, False, {"reason: ": "Must provide state parameter"}, {}
349 # pass post processed data to member operations
350 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
351 data_copy = data.copy()
352 data_copy["system_console"] = filtered_data
353 fos.do_member_operation(
354 "system",
355 "console",
356 data_copy,
357 )
358
359 return fos.set(
360 "system", "console", data=converted_data, vdom=vdom, parameters=parameters
361 )
362
363
364 def is_successful_status(resp):
365 return (
366 "status" in resp
367 and resp["status"] == "success"
368 or "http_status" in resp
369 and resp["http_status"] == 200
370 or "http_method" in resp
371 and resp["http_method"] == "DELETE"
372 and resp["http_status"] == 404
373 )
374
375
376 def fortios_system(data, fos, check_mode):
377
378 if data["system_console"]:
379 resp = system_console(data, fos, check_mode)
380 else:
381 fos._module.fail_json(msg="missing task body: %s" % ("system_console"))
382 if isinstance(resp, tuple) and len(resp) == 4:
383 return resp
384 return (
385 not is_successful_status(resp),
386 is_successful_status(resp)
387 and (resp["revision_changed"] if "revision_changed" in resp else True),
388 resp,
389 {},
390 )
391
392
393 versioned_schema = {
394 "v_range": [["v6.0.0", ""]],
395 "type": "dict",
396 "children": {
397 "output": {
398 "v_range": [["v6.0.0", ""]],
399 "type": "string",
400 "options": [{"value": "standard"}, {"value": "more"}],
401 },
402 "login": {
403 "v_range": [["v6.0.0", ""]],
404 "type": "string",
405 "options": [{"value": "enable"}, {"value": "disable"}],
406 },
407 "fortiexplorer": {
408 "v_range": [["v6.0.0", ""]],
409 "type": "string",
410 "options": [{"value": "enable"}, {"value": "disable"}],
411 },
412 "baudrate": {
413 "v_range": [["v6.0.0", "v7.4.1"]],
414 "type": "string",
415 "options": [
416 {"value": "9600"},
417 {"value": "19200"},
418 {"value": "38400"},
419 {"value": "57600"},
420 {"value": "115200"},
421 ],
422 },
423 "mode": {
424 "v_range": [["v6.0.0", "v7.4.0"]],
425 "type": "string",
426 "options": [{"value": "batch"}, {"value": "line"}],
427 },
428 },
429 }
430
431
432 def main():
433 module_spec = schema_to_module_spec(versioned_schema)
434 mkeyname = None
435 fields = {
436 "access_token": {"required": False, "type": "str", "no_log": True},
437 "enable_log": {"required": False, "type": "bool", "default": False},
438 "vdom": {"required": False, "type": "str", "default": "root"},
439 "member_path": {"required": False, "type": "str"},
440 "member_state": {
441 "type": "str",
442 "required": False,
443 "choices": ["present", "absent"],
444 },
445 "system_console": {
446 "required": False,
447 "type": "dict",
448 "default": None,
449 "options": {},
450 },
451 }
452 for attribute_name in module_spec["options"]:
453 fields["system_console"]["options"][attribute_name] = module_spec["options"][
454 attribute_name
455 ]
456 if mkeyname and mkeyname == attribute_name:
457 fields["system_console"]["options"][attribute_name]["required"] = True
458
459 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
460 check_legacy_fortiosapi(module)
461
462 is_error = False
463 has_changed = False
464 result = None
465 diff = None
466
467 versions_check_result = None
468 if module._socket_path:
469 connection = Connection(module._socket_path)
470 if "access_token" in module.params:
471 connection.set_custom_option("access_token", module.params["access_token"])
472
473 if "enable_log" in module.params:
474 connection.set_custom_option("enable_log", module.params["enable_log"])
475 else:
476 connection.set_custom_option("enable_log", False)
477 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
478 versions_check_result = check_schema_versioning(
479 fos, versioned_schema, "system_console"
480 )
481
482 is_error, has_changed, result, diff = fortios_system(
483 module.params, fos, module.check_mode
484 )
485
486 else:
487 module.fail_json(**FAIL_SOCKET_MSG)
488
489 if versions_check_result and versions_check_result["matched"] is False:
490 module.warn(
491 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
492 )
493
494 if not is_error:
495 if versions_check_result and versions_check_result["matched"] is False:
496 module.exit_json(
497 changed=has_changed,
498 version_check_warning=versions_check_result,
499 meta=result,
500 diff=diff,
501 )
502 else:
503 module.exit_json(changed=has_changed, meta=result, diff=diff)
504 else:
505 if versions_check_result and versions_check_result["matched"] is False:
506 module.fail_json(
507 msg="Error in repo",
508 version_check_warning=versions_check_result,
509 meta=result,
510 )
511 else:
512 module.fail_json(msg="Error in repo", meta=result)
513
514
515 if __name__ == "__main__":
516 main()