Debian Codegraph @

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