Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_wccp.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_wccp
23 short_description: Configure WCCP 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 wccp 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 state:
80 description:
81 - Indicates whether to create or remove the object.
82 type: str
83 required: true
84 choices:
85 - 'present'
86 - 'absent'
87 system_wccp:
88 description:
89 - Configure WCCP.
90 default: null
91 type: dict
92 suboptions:
93 assignment_bucket_format:
94 description:
95 - Assignment bucket format for the WCCP cache engine.
96 type: str
97 choices:
98 - 'wccp-v2'
99 - 'cisco-implementation'
100 assignment_dstaddr_mask:
101 description:
102 - Assignment destination address mask.
103 type: str
104 assignment_method:
105 description:
106 - Hash key assignment preference.
107 type: str
108 choices:
109 - 'HASH'
110 - 'MASK'
111 - 'any'
112 assignment_srcaddr_mask:
113 description:
114 - Assignment source address mask.
115 type: str
116 assignment_weight:
117 description:
118 - Assignment of hash weight/ratio for the WCCP cache engine.
119 type: int
120 authentication:
121 description:
122 - Enable/disable MD5 authentication.
123 type: str
124 choices:
125 - 'enable'
126 - 'disable'
127 cache_engine_method:
128 description:
129 - Method used to forward traffic to the routers or to return to the cache engine.
130 type: str
131 choices:
132 - 'GRE'
133 - 'L2'
134 cache_id:
135 description:
136 - IP address known to all routers. If the addresses are the same, use the default 0.0.0.0.
137 type: str
138 forward_method:
139 description:
140 - Method used to forward traffic to the cache servers.
141 type: str
142 choices:
143 - 'GRE'
144 - 'L2'
145 - 'any'
146 group_address:
147 description:
148 - IP multicast address used by the cache routers. For the FortiGate to ignore multicast WCCP traffic, use the default 0.0.0.0.
149 type: str
150 password:
151 description:
152 - Password for MD5 authentication.
153 type: str
154 ports:
155 description:
156 - Service ports.
157 type: list
158 elements: str
159 ports_defined:
160 description:
161 - Match method.
162 type: str
163 choices:
164 - 'source'
165 - 'destination'
166 primary_hash:
167 description:
168 - Hash method.
169 type: list
170 elements: str
171 choices:
172 - 'src-ip'
173 - 'dst-ip'
174 - 'src-port'
175 - 'dst-port'
176 priority:
177 description:
178 - Service priority.
179 type: int
180 protocol:
181 description:
182 - Service protocol.
183 type: int
184 return_method:
185 description:
186 - Method used to decline a redirected packet and return it to the FortiGate unit.
187 type: str
188 choices:
189 - 'GRE'
190 - 'L2'
191 - 'any'
192 router_id:
193 description:
194 - IP address known to all cache engines. If all cache engines connect to the same FortiGate interface, use the default 0.0.0.0.
195 type: str
196 router_list:
197 description:
198 - IP addresses of one or more WCCP routers.
199 type: list
200 elements: str
201 server_list:
202 description:
203 - IP addresses and netmasks for up to four cache servers.
204 type: list
205 elements: str
206 server_type:
207 description:
208 - Cache server type.
209 type: str
210 choices:
211 - 'forward'
212 - 'proxy'
213 service_id:
214 description:
215 - Service ID.
216 required: true
217 type: str
218 service_type:
219 description:
220 - WCCP service type used by the cache server for logical interception and redirection of traffic.
221 type: str
222 choices:
223 - 'auto'
224 - 'standard'
225 - 'dynamic'
226 """
227
228 EXAMPLES = """
229 - name: Configure WCCP.
230 fortinet.fortios.fortios_system_wccp:
231 vdom: "{{ vdom }}"
232 state: "present"
233 access_token: "<your_own_value>"
234 system_wccp:
235 assignment_bucket_format: "wccp-v2"
236 assignment_dstaddr_mask: "<your_own_value>"
237 assignment_method: "HASH"
238 assignment_srcaddr_mask: "<your_own_value>"
239 assignment_weight: "0"
240 authentication: "enable"
241 cache_engine_method: "GRE"
242 cache_id: "<your_own_value>"
243 forward_method: "GRE"
244 group_address: "<your_own_value>"
245 password: "<your_own_value>"
246 ports: "<your_own_value>"
247 ports_defined: "source"
248 primary_hash: "src-ip"
249 priority: "0"
250 protocol: "0"
251 return_method: "GRE"
252 router_id: "<your_own_value>"
253 router_list: "<your_own_value>"
254 server_list: "<your_own_value>"
255 server_type: "forward"
256 service_id: "<your_own_value>"
257 service_type: "auto"
258 """
259
260 RETURN = """
261 build:
262 description: Build number of the fortigate image
263 returned: always
264 type: str
265 sample: '1547'
266 http_method:
267 description: Last method used to provision the content into FortiGate
268 returned: always
269 type: str
270 sample: 'PUT'
271 http_status:
272 description: Last result given by FortiGate on last operation applied
273 returned: always
274 type: str
275 sample: "200"
276 mkey:
277 description: Master key (id) used in the last call to FortiGate
278 returned: success
279 type: str
280 sample: "id"
281 name:
282 description: Name of the table used to fulfill the request
283 returned: always
284 type: str
285 sample: "urlfilter"
286 path:
287 description: Path of the table used to fulfill the request
288 returned: always
289 type: str
290 sample: "webfilter"
291 revision:
292 description: Internal revision number
293 returned: always
294 type: str
295 sample: "17.0.2.10658"
296 serial:
297 description: Serial number of the unit
298 returned: always
299 type: str
300 sample: "FGVMEVYYQT3AB5352"
301 status:
302 description: Indication of the operation's result
303 returned: always
304 type: str
305 sample: "success"
306 vdom:
307 description: Virtual domain used
308 returned: always
309 type: str
310 sample: "root"
311 version:
312 description: Version of the FortiGate
313 returned: always
314 type: str
315 sample: "v5.6.3"
316 """
317 from ansible.module_utils.basic import AnsibleModule
318 from ansible.module_utils.connection import Connection
319 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
320 FortiOSHandler,
321 )
322 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
323 check_legacy_fortiosapi,
324 )
325 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
326 schema_to_module_spec,
327 )
328 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
329 check_schema_versioning,
330 )
331 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
332 FAIL_SOCKET_MSG,
333 )
334 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
335 remove_invalid_fields,
336 )
337 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
338 is_same_comparison,
339 )
340 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
341 serialize,
342 )
343 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
344 find_current_values,
345 )
346 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
347 unify_data_format,
348 )
349
350
351 def filter_system_wccp_data(json):
352 option_list = [
353 "assignment_bucket_format",
354 "assignment_dstaddr_mask",
355 "assignment_method",
356 "assignment_srcaddr_mask",
357 "assignment_weight",
358 "authentication",
359 "cache_engine_method",
360 "cache_id",
361 "forward_method",
362 "group_address",
363 "password",
364 "ports",
365 "ports_defined",
366 "primary_hash",
367 "priority",
368 "protocol",
369 "return_method",
370 "router_id",
371 "router_list",
372 "server_list",
373 "server_type",
374 "service_id",
375 "service_type",
376 ]
377
378 json = remove_invalid_fields(json)
379 dictionary = {}
380
381 for attribute in option_list:
382 if attribute in json and json[attribute] is not None:
383 dictionary[attribute] = json[attribute]
384
385 return dictionary
386
387
388 def flatten_single_path(data, path, index):
389 if (
390 not data
391 or index == len(path)
392 or path[index] not in data
393 or (not data[path[index]] and not isinstance(data[path[index]], list))
394 ):
395 return
396
397 if index == len(path) - 1:
398 data[path[index]] = " ".join(str(elem) for elem in data[path[index]])
399 if len(data[path[index]]) == 0:
400 data[path[index]] = None
401 elif isinstance(data[path[index]], list):
402 for value in data[path[index]]:
403 flatten_single_path(value, path, index + 1)
404 else:
405 flatten_single_path(data[path[index]], path, index + 1)
406
407
408 def flatten_multilists_attributes(data):
409 multilist_attrs = [
410 ["server_list"],
411 ["router_list"],
412 ["ports"],
413 ["primary_hash"],
414 ]
415
416 for attr in multilist_attrs:
417 flatten_single_path(data, attr, 0)
418
419 return data
420
421
422 def underscore_to_hyphen(data):
423 new_data = None
424 if isinstance(data, list):
425 new_data = []
426 for i, elem in enumerate(data):
427 new_data.append(underscore_to_hyphen(elem))
428 elif isinstance(data, dict):
429 new_data = {}
430 for k, v in data.items():
431 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
432 else:
433 return data
434 return new_data
435
436
437 def system_wccp(data, fos, check_mode=False):
438
439 state = None
440 vdom = data["vdom"]
441 parameters = None
442 state = data.get("state", None)
443 system_wccp_data = data["system_wccp"]
444
445 filtered_data = filter_system_wccp_data(system_wccp_data)
446 filtered_data = flatten_multilists_attributes(filtered_data)
447 converted_data = underscore_to_hyphen(filtered_data)
448
449 # check_mode starts from here
450 if check_mode:
451 diff = {
452 "before": "",
453 "after": filtered_data,
454 }
455 mkeyname = fos.get_mkeyname(None, None)
456 mkey = fos.get_mkey("system", "wccp", filtered_data, vdom=vdom)
457 current_data = fos.get(
458 "system", "wccp", vdom=vdom, mkey=mkey, parameters=parameters
459 )
460 is_existed = (
461 current_data
462 and current_data.get("http_status") == 200
463 and (
464 mkeyname
465 and isinstance(current_data.get("results"), list)
466 and len(current_data["results"]) > 0
467 or not mkeyname
468 and current_data["results"] # global object response
469 )
470 )
471
472 # 2. if it exists and the state is 'present' then compare current settings with desired
473 if state == "present" or state is True or state is None:
474 # for non global modules, mkeyname must exist and it's a new module when mkey is None
475 if mkeyname is not None and mkey is None:
476 return False, True, filtered_data, diff
477
478 # if mkey exists then compare each other
479 # record exits and they're matched or not
480 copied_filtered_data = filtered_data.copy()
481 copied_filtered_data.pop(mkeyname, None)
482 unified_filtered_data = unify_data_format(copied_filtered_data)
483
484 current_data_results = current_data.get("results", {})
485 current_config = (
486 current_data_results[0]
487 if mkeyname
488 and isinstance(current_data_results, list)
489 and len(current_data_results) > 0
490 else current_data_results
491 )
492 if is_existed:
493 unified_current_values = find_current_values(
494 unified_filtered_data,
495 unify_data_format(current_config),
496 )
497
498 is_same = is_same_comparison(
499 serialize(unified_current_values), serialize(unified_filtered_data)
500 )
501
502 return (
503 False,
504 not is_same,
505 filtered_data,
506 {"before": unified_current_values, "after": unified_filtered_data},
507 )
508
509 # record does not exist
510 return False, True, filtered_data, diff
511
512 if state == "absent":
513 if mkey is None:
514 return (
515 False,
516 False,
517 filtered_data,
518 {"before": current_data["results"][0], "after": ""},
519 )
520
521 if is_existed:
522 return (
523 False,
524 True,
525 filtered_data,
526 {"before": current_data["results"][0], "after": ""},
527 )
528 return False, False, filtered_data, {}
529
530 return True, False, {"reason: ": "Must provide state parameter"}, {}
531 # pass post processed data to member operations
532 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
533 data_copy = data.copy()
534 data_copy["system_wccp"] = filtered_data
535 fos.do_member_operation(
536 "system",
537 "wccp",
538 data_copy,
539 )
540
541 if state == "present" or state is True:
542 return fos.set(
543 "system", "wccp", data=converted_data, vdom=vdom, parameters=parameters
544 )
545
546 elif state == "absent":
547 return fos.delete(
548 "system",
549 "wccp",
550 mkey=converted_data["service-id"],
551 vdom=vdom,
552 parameters=parameters,
553 )
554 else:
555 fos._module.fail_json(msg="state must be present or absent!")
556
557
558 def is_successful_status(resp):
559 return (
560 "status" in resp
561 and resp["status"] == "success"
562 or "http_status" in resp
563 and resp["http_status"] == 200
564 or "http_method" in resp
565 and resp["http_method"] == "DELETE"
566 and resp["http_status"] == 404
567 )
568
569
570 def fortios_system(data, fos, check_mode):
571
572 if data["system_wccp"]:
573 resp = system_wccp(data, fos, check_mode)
574 else:
575 fos._module.fail_json(msg="missing task body: %s" % ("system_wccp"))
576 if isinstance(resp, tuple) and len(resp) == 4:
577 return resp
578 return (
579 not is_successful_status(resp),
580 is_successful_status(resp)
581 and (resp["revision_changed"] if "revision_changed" in resp else True),
582 resp,
583 {},
584 )
585
586
587 versioned_schema = {
588 "type": "list",
589 "elements": "dict",
590 "children": {
591 "service_id": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
592 "router_id": {"v_range": [["v6.0.0", ""]], "type": "string"},
593 "cache_id": {"v_range": [["v6.0.0", ""]], "type": "string"},
594 "group_address": {"v_range": [["v6.0.0", ""]], "type": "string"},
595 "server_list": {
596 "v_range": [["v6.0.0", ""]],
597 "type": "list",
598 "multiple_values": True,
599 "elements": "str",
600 },
601 "router_list": {
602 "v_range": [["v6.0.0", ""]],
603 "type": "list",
604 "multiple_values": True,
605 "elements": "str",
606 },
607 "ports_defined": {
608 "v_range": [["v6.0.0", ""]],
609 "type": "string",
610 "options": [{"value": "source"}, {"value": "destination"}],
611 },
612 "server_type": {
613 "v_range": [["v6.0.0", ""]],
614 "type": "string",
615 "options": [{"value": "forward"}, {"value": "proxy"}],
616 },
617 "ports": {
618 "v_range": [["v6.0.0", ""]],
619 "type": "list",
620 "multiple_values": True,
621 "elements": "str",
622 },
623 "authentication": {
624 "v_range": [["v6.0.0", ""]],
625 "type": "string",
626 "options": [{"value": "enable"}, {"value": "disable"}],
627 },
628 "password": {"v_range": [["v6.0.0", ""]], "type": "string"},
629 "forward_method": {
630 "v_range": [["v6.0.0", ""]],
631 "type": "string",
632 "options": [{"value": "GRE"}, {"value": "L2"}, {"value": "any"}],
633 },
634 "cache_engine_method": {
635 "v_range": [["v6.0.0", ""]],
636 "type": "string",
637 "options": [{"value": "GRE"}, {"value": "L2"}],
638 },
639 "service_type": {
640 "v_range": [["v6.0.0", ""]],
641 "type": "string",
642 "options": [{"value": "auto"}, {"value": "standard"}, {"value": "dynamic"}],
643 },
644 "primary_hash": {
645 "v_range": [["v6.0.0", ""]],
646 "type": "list",
647 "options": [
648 {"value": "src-ip"},
649 {"value": "dst-ip"},
650 {"value": "src-port"},
651 {"value": "dst-port"},
652 ],
653 "multiple_values": True,
654 "elements": "str",
655 },
656 "priority": {"v_range": [["v6.0.0", ""]], "type": "integer"},
657 "protocol": {"v_range": [["v6.0.0", ""]], "type": "integer"},
658 "assignment_weight": {"v_range": [["v6.0.0", ""]], "type": "integer"},
659 "assignment_bucket_format": {
660 "v_range": [["v6.0.0", ""]],
661 "type": "string",
662 "options": [{"value": "wccp-v2"}, {"value": "cisco-implementation"}],
663 },
664 "return_method": {
665 "v_range": [["v6.0.0", ""]],
666 "type": "string",
667 "options": [{"value": "GRE"}, {"value": "L2"}, {"value": "any"}],
668 },
669 "assignment_method": {
670 "v_range": [["v6.0.0", ""]],
671 "type": "string",
672 "options": [{"value": "HASH"}, {"value": "MASK"}, {"value": "any"}],
673 },
674 "assignment_srcaddr_mask": {"v_range": [["v6.0.0", ""]], "type": "string"},
675 "assignment_dstaddr_mask": {"v_range": [["v6.0.0", ""]], "type": "string"},
676 },
677 "v_range": [["v6.0.0", ""]],
678 }
679
680
681 def main():
682 module_spec = schema_to_module_spec(versioned_schema)
683 mkeyname = "service_id"
684 fields = {
685 "access_token": {"required": False, "type": "str", "no_log": True},
686 "enable_log": {"required": False, "type": "bool", "default": False},
687 "vdom": {"required": False, "type": "str", "default": "root"},
688 "member_path": {"required": False, "type": "str"},
689 "member_state": {
690 "type": "str",
691 "required": False,
692 "choices": ["present", "absent"],
693 },
694 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
695 "system_wccp": {
696 "required": False,
697 "type": "dict",
698 "default": None,
699 "options": {},
700 },
701 }
702 for attribute_name in module_spec["options"]:
703 fields["system_wccp"]["options"][attribute_name] = module_spec["options"][
704 attribute_name
705 ]
706 if mkeyname and mkeyname == attribute_name:
707 fields["system_wccp"]["options"][attribute_name]["required"] = True
708
709 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
710 check_legacy_fortiosapi(module)
711
712 is_error = False
713 has_changed = False
714 result = None
715 diff = None
716
717 versions_check_result = None
718 if module._socket_path:
719 connection = Connection(module._socket_path)
720 if "access_token" in module.params:
721 connection.set_custom_option("access_token", module.params["access_token"])
722
723 if "enable_log" in module.params:
724 connection.set_custom_option("enable_log", module.params["enable_log"])
725 else:
726 connection.set_custom_option("enable_log", False)
727 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
728 versions_check_result = check_schema_versioning(
729 fos, versioned_schema, "system_wccp"
730 )
731
732 is_error, has_changed, result, diff = fortios_system(
733 module.params, fos, module.check_mode
734 )
735
736 else:
737 module.fail_json(**FAIL_SOCKET_MSG)
738
739 if versions_check_result and versions_check_result["matched"] is False:
740 module.warn(
741 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
742 )
743
744 if not is_error:
745 if versions_check_result and versions_check_result["matched"] is False:
746 module.exit_json(
747 changed=has_changed,
748 version_check_warning=versions_check_result,
749 meta=result,
750 diff=diff,
751 )
752 else:
753 module.exit_json(changed=has_changed, meta=result, diff=diff)
754 else:
755 if versions_check_result and versions_check_result["matched"] is False:
756 module.fail_json(
757 msg="Error in repo",
758 version_check_warning=versions_check_result,
759 meta=result,
760 )
761 else:
762 module.fail_json(msg="Error in repo", meta=result)
763
764
765 if __name__ == "__main__":
766 main()