Debian Codegraph @

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