Debian Codegraph @

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