Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_netflow.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_netflow
23 short_description: Configure NetFlow 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 netflow 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_netflow:
80 description:
81 - Configure NetFlow.
82 default: null
83 type: dict
84 suboptions:
85 active_flow_timeout:
86 description:
87 - Timeout to report active flows (60 - 3600 sec).
88 type: int
89 collector_ip:
90 description:
91 - Collector IP.
92 type: str
93 collector_port:
94 description:
95 - NetFlow collector port number.
96 type: int
97 collectors:
98 description:
99 - Netflow collectors.
100 type: list
101 elements: dict
102 suboptions:
103 collector_ip:
104 description:
105 - Collector IP.
106 type: str
107 collector_port:
108 description:
109 - NetFlow collector port number.
110 type: int
111 id:
112 description:
113 - ID. see <a href='#notes'>Notes</a>.
114 required: true
115 type: int
116 interface:
117 description:
118 - Specify outgoing interface to reach server. Source system.interface.name.
119 type: str
120 interface_select_method:
121 description:
122 - Specify how to select outgoing interface to reach server.
123 type: str
124 choices:
125 - 'auto'
126 - 'sdwan'
127 - 'specify'
128 source_ip:
129 description:
130 - Source IP address for communication with the NetFlow agent.
131 type: str
132 source_ip_interface:
133 description:
134 - Name of the interface used to determine the source IP for exporting packets. Source system.interface.name.
135 type: str
136 vrf_select:
137 description:
138 - VRF ID used for connection to server.
139 type: int
140 exclusion_filters:
141 description:
142 - Exclusion filters
143 type: list
144 elements: dict
145 suboptions:
146 destination_ip:
147 description:
148 - Session destination address.
149 type: str
150 destination_port:
151 description:
152 - Session destination port number or range.
153 type: str
154 id:
155 description:
156 - Filter ID. see <a href='#notes'>Notes</a>.
157 required: true
158 type: int
159 protocol:
160 description:
161 - Session IP protocol (0 - 255).
162 type: int
163 source_ip:
164 description:
165 - Session source address.
166 type: str
167 source_port:
168 description:
169 - Session source port number or range.
170 type: str
171 inactive_flow_timeout:
172 description:
173 - Timeout for periodic report of finished flows (10 - 600 sec).
174 type: int
175 interface:
176 description:
177 - Specify outgoing interface to reach server. Source system.interface.name.
178 type: str
179 interface_select_method:
180 description:
181 - Specify how to select outgoing interface to reach server.
182 type: str
183 choices:
184 - 'auto'
185 - 'sdwan'
186 - 'specify'
187 session_cache_size:
188 description:
189 - Maximum RAM usage allowed for Netflow session cache.
190 type: str
191 choices:
192 - 'min'
193 - 'default'
194 - 'max'
195 source_ip:
196 description:
197 - Source IP address for communication with the NetFlow agent.
198 type: str
199 template_tx_counter:
200 description:
201 - Counter of flowset records before resending a template flowset record.
202 type: int
203 template_tx_timeout:
204 description:
205 - Timeout for periodic template flowset transmission (60 - 86400 sec).
206 type: int
207 """
208
209 EXAMPLES = """
210 - name: Configure NetFlow.
211 fortinet.fortios.fortios_system_netflow:
212 vdom: "{{ vdom }}"
213 system_netflow:
214 active_flow_timeout: "1800"
215 collector_ip: "<your_own_value>"
216 collector_port: "2055"
217 collectors:
218 -
219 collector_ip: "<your_own_value>"
220 collector_port: "2055"
221 id: "9"
222 interface: "<your_own_value> (source system.interface.name)"
223 interface_select_method: "auto"
224 source_ip: "84.230.14.43"
225 source_ip_interface: "<your_own_value> (source system.interface.name)"
226 vrf_select: "0"
227 exclusion_filters:
228 -
229 destination_ip: "<your_own_value>"
230 destination_port: "<your_own_value>"
231 id: "18"
232 protocol: "255"
233 source_ip: "84.230.14.43"
234 source_port: "<your_own_value>"
235 inactive_flow_timeout: "15"
236 interface: "<your_own_value> (source system.interface.name)"
237 interface_select_method: "auto"
238 session_cache_size: "min"
239 source_ip: "84.230.14.43"
240 template_tx_counter: "20"
241 template_tx_timeout: "1800"
242 """
243
244 RETURN = """
245 build:
246 description: Build number of the fortigate image
247 returned: always
248 type: str
249 sample: '1547'
250 http_method:
251 description: Last method used to provision the content into FortiGate
252 returned: always
253 type: str
254 sample: 'PUT'
255 http_status:
256 description: Last result given by FortiGate on last operation applied
257 returned: always
258 type: str
259 sample: "200"
260 mkey:
261 description: Master key (id) used in the last call to FortiGate
262 returned: success
263 type: str
264 sample: "id"
265 name:
266 description: Name of the table used to fulfill the request
267 returned: always
268 type: str
269 sample: "urlfilter"
270 path:
271 description: Path of the table used to fulfill the request
272 returned: always
273 type: str
274 sample: "webfilter"
275 revision:
276 description: Internal revision number
277 returned: always
278 type: str
279 sample: "17.0.2.10658"
280 serial:
281 description: Serial number of the unit
282 returned: always
283 type: str
284 sample: "FGVMEVYYQT3AB5352"
285 status:
286 description: Indication of the operation's result
287 returned: always
288 type: str
289 sample: "success"
290 vdom:
291 description: Virtual domain used
292 returned: always
293 type: str
294 sample: "root"
295 version:
296 description: Version of the FortiGate
297 returned: always
298 type: str
299 sample: "v5.6.3"
300 """
301 from ansible.module_utils.basic import AnsibleModule
302 from ansible.module_utils.connection import Connection
303 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
304 FortiOSHandler,
305 )
306 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
307 check_legacy_fortiosapi,
308 )
309 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
310 schema_to_module_spec,
311 )
312 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
313 check_schema_versioning,
314 )
315 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
316 FAIL_SOCKET_MSG,
317 )
318 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
319 remove_invalid_fields,
320 )
321 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
322 is_same_comparison,
323 )
324 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
325 serialize,
326 )
327 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
328 find_current_values,
329 )
330 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
331 unify_data_format,
332 )
333
334
335 def filter_system_netflow_data(json):
336 option_list = [
337 "active_flow_timeout",
338 "collector_ip",
339 "collector_port",
340 "collectors",
341 "exclusion_filters",
342 "inactive_flow_timeout",
343 "interface",
344 "interface_select_method",
345 "session_cache_size",
346 "source_ip",
347 "template_tx_counter",
348 "template_tx_timeout",
349 ]
350
351 json = remove_invalid_fields(json)
352 dictionary = {}
353
354 for attribute in option_list:
355 if attribute in json and json[attribute] is not None:
356 dictionary[attribute] = json[attribute]
357
358 return dictionary
359
360
361 def underscore_to_hyphen(data):
362 new_data = None
363 if isinstance(data, list):
364 new_data = []
365 for i, elem in enumerate(data):
366 new_data.append(underscore_to_hyphen(elem))
367 elif isinstance(data, dict):
368 new_data = {}
369 for k, v in data.items():
370 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
371 else:
372 return data
373 return new_data
374
375
376 def system_netflow(data, fos, check_mode=False):
377
378 state = None
379 vdom = data["vdom"]
380 parameters = None
381 state = data.get("state", None)
382 system_netflow_data = data["system_netflow"]
383
384 filtered_data = filter_system_netflow_data(system_netflow_data)
385 converted_data = underscore_to_hyphen(filtered_data)
386
387 # check_mode starts from here
388 if check_mode:
389 diff = {
390 "before": "",
391 "after": filtered_data,
392 }
393 mkeyname = fos.get_mkeyname(None, None)
394 mkey = fos.get_mkey("system", "netflow", filtered_data, vdom=vdom)
395 current_data = fos.get(
396 "system", "netflow", vdom=vdom, mkey=mkey, parameters=parameters
397 )
398 is_existed = (
399 current_data
400 and current_data.get("http_status") == 200
401 and (
402 mkeyname
403 and isinstance(current_data.get("results"), list)
404 and len(current_data["results"]) > 0
405 or not mkeyname
406 and current_data["results"] # global object response
407 )
408 )
409
410 # 2. if it exists and the state is 'present' then compare current settings with desired
411 if state == "present" or state is True or state is None:
412 # for non global modules, mkeyname must exist and it's a new module when mkey is None
413 if mkeyname is not None and mkey is None:
414 return False, True, filtered_data, diff
415
416 # if mkey exists then compare each other
417 # record exits and they're matched or not
418 copied_filtered_data = filtered_data.copy()
419 copied_filtered_data.pop(mkeyname, None)
420 unified_filtered_data = unify_data_format(copied_filtered_data)
421
422 current_data_results = current_data.get("results", {})
423 current_config = (
424 current_data_results[0]
425 if mkeyname
426 and isinstance(current_data_results, list)
427 and len(current_data_results) > 0
428 else current_data_results
429 )
430 if is_existed:
431 unified_current_values = find_current_values(
432 unified_filtered_data,
433 unify_data_format(current_config),
434 )
435
436 is_same = is_same_comparison(
437 serialize(unified_current_values), serialize(unified_filtered_data)
438 )
439
440 return (
441 False,
442 not is_same,
443 filtered_data,
444 {"before": unified_current_values, "after": unified_filtered_data},
445 )
446
447 # record does not exist
448 return False, True, filtered_data, diff
449
450 if state == "absent":
451 if mkey is None:
452 return (
453 False,
454 False,
455 filtered_data,
456 {"before": current_data["results"][0], "after": ""},
457 )
458
459 if is_existed:
460 return (
461 False,
462 True,
463 filtered_data,
464 {"before": current_data["results"][0], "after": ""},
465 )
466 return False, False, filtered_data, {}
467
468 return True, False, {"reason: ": "Must provide state parameter"}, {}
469 # pass post processed data to member operations
470 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
471 data_copy = data.copy()
472 data_copy["system_netflow"] = filtered_data
473 fos.do_member_operation(
474 "system",
475 "netflow",
476 data_copy,
477 )
478
479 return fos.set(
480 "system", "netflow", data=converted_data, vdom=vdom, parameters=parameters
481 )
482
483
484 def is_successful_status(resp):
485 return (
486 "status" in resp
487 and resp["status"] == "success"
488 or "http_status" in resp
489 and resp["http_status"] == 200
490 or "http_method" in resp
491 and resp["http_method"] == "DELETE"
492 and resp["http_status"] == 404
493 )
494
495
496 def fortios_system(data, fos, check_mode):
497
498 if data["system_netflow"]:
499 resp = system_netflow(data, fos, check_mode)
500 else:
501 fos._module.fail_json(msg="missing task body: %s" % ("system_netflow"))
502 if isinstance(resp, tuple) and len(resp) == 4:
503 return resp
504 return (
505 not is_successful_status(resp),
506 is_successful_status(resp)
507 and (resp["revision_changed"] if "revision_changed" in resp else True),
508 resp,
509 {},
510 )
511
512
513 versioned_schema = {
514 "v_range": [["v6.0.0", ""]],
515 "type": "dict",
516 "children": {
517 "active_flow_timeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
518 "inactive_flow_timeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
519 "template_tx_timeout": {"v_range": [["v6.0.0", ""]], "type": "integer"},
520 "template_tx_counter": {"v_range": [["v6.0.0", ""]], "type": "integer"},
521 "session_cache_size": {
522 "v_range": [["v7.6.3", ""]],
523 "type": "string",
524 "options": [{"value": "min"}, {"value": "default"}, {"value": "max"}],
525 },
526 "exclusion_filters": {
527 "type": "list",
528 "elements": "dict",
529 "children": {
530 "id": {
531 "v_range": [["v7.6.0", ""]],
532 "type": "integer",
533 "required": True,
534 },
535 "source_ip": {"v_range": [["v7.6.0", ""]], "type": "string"},
536 "destination_ip": {"v_range": [["v7.6.0", ""]], "type": "string"},
537 "source_port": {"v_range": [["v7.6.0", ""]], "type": "string"},
538 "destination_port": {"v_range": [["v7.6.0", ""]], "type": "string"},
539 "protocol": {"v_range": [["v7.6.0", ""]], "type": "integer"},
540 },
541 "v_range": [["v7.6.0", ""]],
542 },
543 "collectors": {
544 "type": "list",
545 "elements": "dict",
546 "children": {
547 "id": {
548 "v_range": [["v7.4.2", ""]],
549 "type": "integer",
550 "required": True,
551 },
552 "collector_ip": {"v_range": [["v7.4.2", ""]], "type": "string"},
553 "collector_port": {"v_range": [["v7.4.2", ""]], "type": "integer"},
554 "source_ip": {"v_range": [["v7.4.2", ""]], "type": "string"},
555 "source_ip_interface": {"v_range": [["v7.6.0", ""]], "type": "string"},
556 "interface_select_method": {
557 "v_range": [["v7.4.2", ""]],
558 "type": "string",
559 "options": [
560 {"value": "auto"},
561 {"value": "sdwan"},
562 {"value": "specify"},
563 ],
564 },
565 "interface": {"v_range": [["v7.4.2", ""]], "type": "string"},
566 "vrf_select": {"v_range": [["v7.6.1", ""]], "type": "integer"},
567 },
568 "v_range": [["v7.4.2", ""]],
569 },
570 "collector_ip": {"v_range": [["v6.0.0", "v7.4.1"]], "type": "string"},
571 "collector_port": {"v_range": [["v6.0.0", "v7.4.1"]], "type": "integer"},
572 "source_ip": {"v_range": [["v6.0.0", "v7.4.1"]], "type": "string"},
573 "interface_select_method": {
574 "v_range": [["v7.0.1", "v7.4.1"]],
575 "type": "string",
576 "options": [{"value": "auto"}, {"value": "sdwan"}, {"value": "specify"}],
577 },
578 "interface": {"v_range": [["v7.0.1", "v7.4.1"]], "type": "string"},
579 },
580 }
581
582
583 def main():
584 module_spec = schema_to_module_spec(versioned_schema)
585 mkeyname = None
586 fields = {
587 "access_token": {"required": False, "type": "str", "no_log": True},
588 "enable_log": {"required": False, "type": "bool", "default": False},
589 "vdom": {"required": False, "type": "str", "default": "root"},
590 "member_path": {"required": False, "type": "str"},
591 "member_state": {
592 "type": "str",
593 "required": False,
594 "choices": ["present", "absent"],
595 },
596 "system_netflow": {
597 "required": False,
598 "type": "dict",
599 "default": None,
600 "options": {},
601 },
602 }
603 for attribute_name in module_spec["options"]:
604 fields["system_netflow"]["options"][attribute_name] = module_spec["options"][
605 attribute_name
606 ]
607 if mkeyname and mkeyname == attribute_name:
608 fields["system_netflow"]["options"][attribute_name]["required"] = True
609
610 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
611 check_legacy_fortiosapi(module)
612
613 is_error = False
614 has_changed = False
615 result = None
616 diff = None
617
618 versions_check_result = None
619 if module._socket_path:
620 connection = Connection(module._socket_path)
621 if "access_token" in module.params:
622 connection.set_custom_option("access_token", module.params["access_token"])
623
624 if "enable_log" in module.params:
625 connection.set_custom_option("enable_log", module.params["enable_log"])
626 else:
627 connection.set_custom_option("enable_log", False)
628 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
629 versions_check_result = check_schema_versioning(
630 fos, versioned_schema, "system_netflow"
631 )
632
633 is_error, has_changed, result, diff = fortios_system(
634 module.params, fos, module.check_mode
635 )
636
637 else:
638 module.fail_json(**FAIL_SOCKET_MSG)
639
640 if versions_check_result and versions_check_result["matched"] is False:
641 module.warn(
642 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
643 )
644
645 if not is_error:
646 if versions_check_result and versions_check_result["matched"] is False:
647 module.exit_json(
648 changed=has_changed,
649 version_check_warning=versions_check_result,
650 meta=result,
651 diff=diff,
652 )
653 else:
654 module.exit_json(changed=has_changed, meta=result, diff=diff)
655 else:
656 if versions_check_result and versions_check_result["matched"] is False:
657 module.fail_json(
658 msg="Error in repo",
659 version_check_warning=versions_check_result,
660 meta=result,
661 )
662 else:
663 module.fail_json(msg="Error in repo", meta=result)
664
665
666 if __name__ == "__main__":
667 main()