Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_fm.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_fm
23 short_description: Configure FM 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 fm 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_fm:
80 description:
81 - Configure FM.
82 default: null
83 type: dict
84 suboptions:
85 auto_backup:
86 description:
87 - Enable/disable automatic backup.
88 type: str
89 choices:
90 - 'enable'
91 - 'disable'
92 id:
93 description:
94 - ID.
95 type: str
96 ip:
97 description:
98 - IP address.
99 type: str
100 ipsec:
101 description:
102 - Enable/disable IPsec.
103 type: str
104 choices:
105 - 'enable'
106 - 'disable'
107 scheduled_config_restore:
108 description:
109 - Enable/disable scheduled configuration restore.
110 type: str
111 choices:
112 - 'enable'
113 - 'disable'
114 status:
115 description:
116 - Enable/disable FM.
117 type: str
118 choices:
119 - 'enable'
120 - 'disable'
121 vdom:
122 description:
123 - VDOM. Source system.vdom.name.
124 type: str
125 """
126
127 EXAMPLES = """
128 - name: Configure FM.
129 fortinet.fortios.fortios_system_fm:
130 vdom: "{{ vdom }}"
131 system_fm:
132 auto_backup: "enable"
133 id: "4"
134 ip: "<your_own_value>"
135 ipsec: "enable"
136 scheduled_config_restore: "enable"
137 status: "enable"
138 vdom: "<your_own_value> (source system.vdom.name)"
139 """
140
141 RETURN = """
142 build:
143 description: Build number of the fortigate image
144 returned: always
145 type: str
146 sample: '1547'
147 http_method:
148 description: Last method used to provision the content into FortiGate
149 returned: always
150 type: str
151 sample: 'PUT'
152 http_status:
153 description: Last result given by FortiGate on last operation applied
154 returned: always
155 type: str
156 sample: "200"
157 mkey:
158 description: Master key (id) used in the last call to FortiGate
159 returned: success
160 type: str
161 sample: "id"
162 name:
163 description: Name of the table used to fulfill the request
164 returned: always
165 type: str
166 sample: "urlfilter"
167 path:
168 description: Path of the table used to fulfill the request
169 returned: always
170 type: str
171 sample: "webfilter"
172 revision:
173 description: Internal revision number
174 returned: always
175 type: str
176 sample: "17.0.2.10658"
177 serial:
178 description: Serial number of the unit
179 returned: always
180 type: str
181 sample: "FGVMEVYYQT3AB5352"
182 status:
183 description: Indication of the operation's result
184 returned: always
185 type: str
186 sample: "success"
187 vdom:
188 description: Virtual domain used
189 returned: always
190 type: str
191 sample: "root"
192 version:
193 description: Version of the FortiGate
194 returned: always
195 type: str
196 sample: "v5.6.3"
197 """
198 from ansible.module_utils.basic import AnsibleModule
199 from ansible.module_utils.connection import Connection
200 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
201 FortiOSHandler,
202 )
203 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
204 check_legacy_fortiosapi,
205 )
206 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
207 schema_to_module_spec,
208 )
209 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
210 check_schema_versioning,
211 )
212 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
213 FAIL_SOCKET_MSG,
214 )
215 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
216 remove_invalid_fields,
217 )
218 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
219 is_same_comparison,
220 )
221 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
222 serialize,
223 )
224 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
225 find_current_values,
226 )
227 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
228 unify_data_format,
229 )
230
231
232 def filter_system_fm_data(json):
233 option_list = [
234 "auto_backup",
235 "id",
236 "ip",
237 "ipsec",
238 "scheduled_config_restore",
239 "status",
240 "vdom",
241 ]
242
243 json = remove_invalid_fields(json)
244 dictionary = {}
245
246 for attribute in option_list:
247 if attribute in json and json[attribute] is not None:
248 dictionary[attribute] = json[attribute]
249
250 return dictionary
251
252
253 def underscore_to_hyphen(data):
254 new_data = None
255 if isinstance(data, list):
256 new_data = []
257 for i, elem in enumerate(data):
258 new_data.append(underscore_to_hyphen(elem))
259 elif isinstance(data, dict):
260 new_data = {}
261 for k, v in data.items():
262 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
263 else:
264 return data
265 return new_data
266
267
268 def system_fm(data, fos, check_mode=False):
269
270 state = None
271 vdom = data["vdom"]
272 parameters = None
273 state = data.get("state", None)
274 system_fm_data = data["system_fm"]
275
276 filtered_data = filter_system_fm_data(system_fm_data)
277 converted_data = underscore_to_hyphen(filtered_data)
278
279 # check_mode starts from here
280 if check_mode:
281 diff = {
282 "before": "",
283 "after": filtered_data,
284 }
285 mkeyname = fos.get_mkeyname(None, None)
286 mkey = fos.get_mkey("system", "fm", filtered_data, vdom=vdom)
287 current_data = fos.get(
288 "system", "fm", vdom=vdom, mkey=mkey, parameters=parameters
289 )
290 is_existed = (
291 current_data
292 and current_data.get("http_status") == 200
293 and (
294 mkeyname
295 and isinstance(current_data.get("results"), list)
296 and len(current_data["results"]) > 0
297 or not mkeyname
298 and current_data["results"] # global object response
299 )
300 )
301
302 # 2. if it exists and the state is 'present' then compare current settings with desired
303 if state == "present" or state is True or state is None:
304 # for non global modules, mkeyname must exist and it's a new module when mkey is None
305 if mkeyname is not None and mkey is None:
306 return False, True, filtered_data, diff
307
308 # if mkey exists then compare each other
309 # record exits and they're matched or not
310 copied_filtered_data = filtered_data.copy()
311 copied_filtered_data.pop(mkeyname, None)
312 unified_filtered_data = unify_data_format(copied_filtered_data)
313
314 current_data_results = current_data.get("results", {})
315 current_config = (
316 current_data_results[0]
317 if mkeyname
318 and isinstance(current_data_results, list)
319 and len(current_data_results) > 0
320 else current_data_results
321 )
322 if is_existed:
323 unified_current_values = find_current_values(
324 unified_filtered_data,
325 unify_data_format(current_config),
326 )
327
328 is_same = is_same_comparison(
329 serialize(unified_current_values), serialize(unified_filtered_data)
330 )
331
332 return (
333 False,
334 not is_same,
335 filtered_data,
336 {"before": unified_current_values, "after": unified_filtered_data},
337 )
338
339 # record does not exist
340 return False, True, filtered_data, diff
341
342 if state == "absent":
343 if mkey is None:
344 return (
345 False,
346 False,
347 filtered_data,
348 {"before": current_data["results"][0], "after": ""},
349 )
350
351 if is_existed:
352 return (
353 False,
354 True,
355 filtered_data,
356 {"before": current_data["results"][0], "after": ""},
357 )
358 return False, False, filtered_data, {}
359
360 return True, False, {"reason: ": "Must provide state parameter"}, {}
361 # pass post processed data to member operations
362 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
363 data_copy = data.copy()
364 data_copy["system_fm"] = filtered_data
365 fos.do_member_operation(
366 "system",
367 "fm",
368 data_copy,
369 )
370
371 return fos.set(
372 "system", "fm", data=converted_data, vdom=vdom, parameters=parameters
373 )
374
375
376 def is_successful_status(resp):
377 return (
378 "status" in resp
379 and resp["status"] == "success"
380 or "http_status" in resp
381 and resp["http_status"] == 200
382 or "http_method" in resp
383 and resp["http_method"] == "DELETE"
384 and resp["http_status"] == 404
385 )
386
387
388 def fortios_system(data, fos, check_mode):
389
390 if data["system_fm"]:
391 resp = system_fm(data, fos, check_mode)
392 else:
393 fos._module.fail_json(msg="missing task body: %s" % ("system_fm"))
394 if isinstance(resp, tuple) and len(resp) == 4:
395 return resp
396 return (
397 not is_successful_status(resp),
398 is_successful_status(resp)
399 and (resp["revision_changed"] if "revision_changed" in resp else True),
400 resp,
401 {},
402 )
403
404
405 versioned_schema = {
406 "v_range": [["v6.0.0", "v7.0.1"]],
407 "type": "dict",
408 "children": {
409 "status": {
410 "v_range": [["v6.0.0", "v7.0.1"]],
411 "type": "string",
412 "options": [{"value": "enable"}, {"value": "disable"}],
413 },
414 "id": {"v_range": [["v6.0.0", "v7.0.1"]], "type": "string"},
415 "ip": {"v_range": [["v6.0.0", "v7.0.1"]], "type": "string"},
416 "vdom": {"v_range": [["v6.0.0", "v7.0.1"]], "type": "string"},
417 "auto_backup": {
418 "v_range": [["v6.0.0", "v7.0.1"]],
419 "type": "string",
420 "options": [{"value": "enable"}, {"value": "disable"}],
421 },
422 "scheduled_config_restore": {
423 "v_range": [["v6.0.0", "v7.0.1"]],
424 "type": "string",
425 "options": [{"value": "enable"}, {"value": "disable"}],
426 },
427 "ipsec": {
428 "v_range": [["v6.0.0", "v7.0.1"]],
429 "type": "string",
430 "options": [{"value": "enable"}, {"value": "disable"}],
431 },
432 },
433 }
434
435
436 def main():
437 module_spec = schema_to_module_spec(versioned_schema)
438 mkeyname = None
439 fields = {
440 "access_token": {"required": False, "type": "str", "no_log": True},
441 "enable_log": {"required": False, "type": "bool", "default": False},
442 "vdom": {"required": False, "type": "str", "default": "root"},
443 "member_path": {"required": False, "type": "str"},
444 "member_state": {
445 "type": "str",
446 "required": False,
447 "choices": ["present", "absent"],
448 },
449 "system_fm": {
450 "required": False,
451 "type": "dict",
452 "default": None,
453 "options": {},
454 },
455 }
456 for attribute_name in module_spec["options"]:
457 fields["system_fm"]["options"][attribute_name] = module_spec["options"][
458 attribute_name
459 ]
460 if mkeyname and mkeyname == attribute_name:
461 fields["system_fm"]["options"][attribute_name]["required"] = True
462
463 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
464 check_legacy_fortiosapi(module)
465
466 is_error = False
467 has_changed = False
468 result = None
469 diff = None
470
471 versions_check_result = None
472 if module._socket_path:
473 connection = Connection(module._socket_path)
474 if "access_token" in module.params:
475 connection.set_custom_option("access_token", module.params["access_token"])
476
477 if "enable_log" in module.params:
478 connection.set_custom_option("enable_log", module.params["enable_log"])
479 else:
480 connection.set_custom_option("enable_log", False)
481 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
482 versions_check_result = check_schema_versioning(
483 fos, versioned_schema, "system_fm"
484 )
485
486 is_error, has_changed, result, diff = fortios_system(
487 module.params, fos, module.check_mode
488 )
489
490 else:
491 module.fail_json(**FAIL_SOCKET_MSG)
492
493 if versions_check_result and versions_check_result["matched"] is False:
494 module.warn(
495 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
496 )
497
498 if not is_error:
499 if versions_check_result and versions_check_result["matched"] is False:
500 module.exit_json(
501 changed=has_changed,
502 version_check_warning=versions_check_result,
503 meta=result,
504 diff=diff,
505 )
506 else:
507 module.exit_json(changed=has_changed, meta=result, diff=diff)
508 else:
509 if versions_check_result and versions_check_result["matched"] is False:
510 module.fail_json(
511 msg="Error in repo",
512 version_check_warning=versions_check_result,
513 meta=result,
514 )
515 else:
516 module.fail_json(msg="Error in repo", meta=result)
517
518
519 if __name__ == "__main__":
520 main()