Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_evpn.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_evpn
23 short_description: Configure EVPN instance 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 evpn 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 - We highly recommend using your own value as the id instead of 0, while '0' is a special placeholder that allows the backend to assign the latest
39 available number for the object, it does have limitations. Please find more details in Q&A.
40 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
41
42 - The module supports check_mode.
43
44 requirements:
45 - ansible>=2.16
46 options:
47 access_token:
48 description:
49 - Token-based authentication.
50 Generated from GUI of Fortigate.
51 type: str
52 required: false
53 enable_log:
54 description:
55 - Enable/Disable logging for task.
56 type: bool
57 required: false
58 default: false
59 vdom:
60 description:
61 - Virtual domain, among those defined previously. A vdom is a
62 virtual instance of the FortiGate that can be configured and
63 used as a different unit.
64 type: str
65 default: root
66 member_path:
67 type: str
68 description:
69 - Member attribute path to operate on.
70 - Delimited by a slash character if there are more than one attribute.
71 - Parameter marked with member_path is legitimate for doing member operation.
72 member_state:
73 type: str
74 description:
75 - Add or delete a member under specified attribute path.
76 - When member_state is specified, the state option is ignored.
77 choices:
78 - 'present'
79 - 'absent'
80
81 state:
82 description:
83 - Indicates whether to create or remove the object.
84 type: str
85 required: true
86 choices:
87 - 'present'
88 - 'absent'
89 system_evpn:
90 description:
91 - Configure EVPN instance.
92 default: null
93 type: dict
94 suboptions:
95 arp_suppression:
96 description:
97 - Enable/disable ARP suppression.
98 type: str
99 choices:
100 - 'enable'
101 - 'disable'
102 export_rt:
103 description:
104 - List of export route targets.
105 type: list
106 elements: dict
107 suboptions:
108 route_target:
109 description:
110 - 'Route target: AA:NN|A.B.C.D:NN.'
111 required: true
112 type: str
113 id:
114 description:
115 - ID. see <a href='#notes'>Notes</a>.
116 required: true
117 type: int
118 import_rt:
119 description:
120 - List of import route targets.
121 type: list
122 elements: dict
123 suboptions:
124 route_target:
125 description:
126 - 'Route target: AA:NN|A.B.C.D:NN.'
127 required: true
128 type: str
129 ip_local_learning:
130 description:
131 - Enable/disable IP address local learning.
132 type: str
133 choices:
134 - 'enable'
135 - 'disable'
136 rd:
137 description:
138 - 'Route Distinguisher: AA:NN|A.B.C.D:NN.'
139 type: str
140 """
141
142 EXAMPLES = """
143 - name: Configure EVPN instance.
144 fortinet.fortios.fortios_system_evpn:
145 vdom: "{{ vdom }}"
146 state: "present"
147 access_token: "<your_own_value>"
148 system_evpn:
149 arp_suppression: "enable"
150 export_rt:
151 -
152 route_target: "<your_own_value>"
153 id: "6"
154 import_rt:
155 -
156 route_target: "<your_own_value>"
157 ip_local_learning: "enable"
158 rd: "<your_own_value>"
159 """
160
161 RETURN = """
162 build:
163 description: Build number of the fortigate image
164 returned: always
165 type: str
166 sample: '1547'
167 http_method:
168 description: Last method used to provision the content into FortiGate
169 returned: always
170 type: str
171 sample: 'PUT'
172 http_status:
173 description: Last result given by FortiGate on last operation applied
174 returned: always
175 type: str
176 sample: "200"
177 mkey:
178 description: Master key (id) used in the last call to FortiGate
179 returned: success
180 type: str
181 sample: "id"
182 name:
183 description: Name of the table used to fulfill the request
184 returned: always
185 type: str
186 sample: "urlfilter"
187 path:
188 description: Path of the table used to fulfill the request
189 returned: always
190 type: str
191 sample: "webfilter"
192 revision:
193 description: Internal revision number
194 returned: always
195 type: str
196 sample: "17.0.2.10658"
197 serial:
198 description: Serial number of the unit
199 returned: always
200 type: str
201 sample: "FGVMEVYYQT3AB5352"
202 status:
203 description: Indication of the operation's result
204 returned: always
205 type: str
206 sample: "success"
207 vdom:
208 description: Virtual domain used
209 returned: always
210 type: str
211 sample: "root"
212 version:
213 description: Version of the FortiGate
214 returned: always
215 type: str
216 sample: "v5.6.3"
217 """
218 from ansible.module_utils.basic import AnsibleModule
219 from ansible.module_utils.connection import Connection
220 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
221 FortiOSHandler,
222 )
223 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
224 check_legacy_fortiosapi,
225 )
226 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
227 schema_to_module_spec,
228 )
229 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
230 check_schema_versioning,
231 )
232 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
233 FAIL_SOCKET_MSG,
234 )
235 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
236 remove_invalid_fields,
237 )
238 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
239 is_same_comparison,
240 )
241 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
242 serialize,
243 )
244 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
245 find_current_values,
246 )
247 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
248 unify_data_format,
249 )
250
251
252 def filter_system_evpn_data(json):
253 option_list = [
254 "arp_suppression",
255 "export_rt",
256 "id",
257 "import_rt",
258 "ip_local_learning",
259 "rd",
260 ]
261
262 json = remove_invalid_fields(json)
263 dictionary = {}
264
265 for attribute in option_list:
266 if attribute in json and json[attribute] is not None:
267 dictionary[attribute] = json[attribute]
268
269 return dictionary
270
271
272 def underscore_to_hyphen(data):
273 new_data = None
274 if isinstance(data, list):
275 new_data = []
276 for i, elem in enumerate(data):
277 new_data.append(underscore_to_hyphen(elem))
278 elif isinstance(data, dict):
279 new_data = {}
280 for k, v in data.items():
281 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
282 else:
283 return data
284 return new_data
285
286
287 def system_evpn(data, fos, check_mode=False):
288
289 state = None
290 vdom = data["vdom"]
291 parameters = None
292 state = data.get("state", None)
293 system_evpn_data = data["system_evpn"]
294
295 filtered_data = filter_system_evpn_data(system_evpn_data)
296 converted_data = underscore_to_hyphen(filtered_data)
297
298 # check_mode starts from here
299 if check_mode:
300 diff = {
301 "before": "",
302 "after": filtered_data,
303 }
304 mkeyname = fos.get_mkeyname(None, None)
305 mkey = fos.get_mkey("system", "evpn", filtered_data, vdom=vdom)
306 current_data = fos.get(
307 "system", "evpn", vdom=vdom, mkey=mkey, parameters=parameters
308 )
309 is_existed = (
310 current_data
311 and current_data.get("http_status") == 200
312 and (
313 mkeyname
314 and isinstance(current_data.get("results"), list)
315 and len(current_data["results"]) > 0
316 or not mkeyname
317 and current_data["results"] # global object response
318 )
319 )
320
321 # 2. if it exists and the state is 'present' then compare current settings with desired
322 if state == "present" or state is True or state is None:
323 # for non global modules, mkeyname must exist and it's a new module when mkey is None
324 if mkeyname is not None and mkey is None:
325 return False, True, filtered_data, diff
326
327 # if mkey exists then compare each other
328 # record exits and they're matched or not
329 copied_filtered_data = filtered_data.copy()
330 copied_filtered_data.pop(mkeyname, None)
331 unified_filtered_data = unify_data_format(copied_filtered_data)
332
333 current_data_results = current_data.get("results", {})
334 current_config = (
335 current_data_results[0]
336 if mkeyname
337 and isinstance(current_data_results, list)
338 and len(current_data_results) > 0
339 else current_data_results
340 )
341 if is_existed:
342 unified_current_values = find_current_values(
343 unified_filtered_data,
344 unify_data_format(current_config),
345 )
346
347 is_same = is_same_comparison(
348 serialize(unified_current_values), serialize(unified_filtered_data)
349 )
350
351 return (
352 False,
353 not is_same,
354 filtered_data,
355 {"before": unified_current_values, "after": unified_filtered_data},
356 )
357
358 # record does not exist
359 return False, True, filtered_data, diff
360
361 if state == "absent":
362 if mkey is None:
363 return (
364 False,
365 False,
366 filtered_data,
367 {"before": current_data["results"][0], "after": ""},
368 )
369
370 if is_existed:
371 return (
372 False,
373 True,
374 filtered_data,
375 {"before": current_data["results"][0], "after": ""},
376 )
377 return False, False, filtered_data, {}
378
379 return True, False, {"reason: ": "Must provide state parameter"}, {}
380 # pass post processed data to member operations
381 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
382 data_copy = data.copy()
383 data_copy["system_evpn"] = filtered_data
384 fos.do_member_operation(
385 "system",
386 "evpn",
387 data_copy,
388 )
389
390 if state == "present" or state is True:
391 return fos.set(
392 "system", "evpn", data=converted_data, vdom=vdom, parameters=parameters
393 )
394
395 elif state == "absent":
396 return fos.delete(
397 "system",
398 "evpn",
399 mkey=converted_data["id"],
400 vdom=vdom,
401 parameters=parameters,
402 )
403 else:
404 fos._module.fail_json(msg="state must be present or absent!")
405
406
407 def is_successful_status(resp):
408 return (
409 "status" in resp
410 and resp["status"] == "success"
411 or "http_status" in resp
412 and resp["http_status"] == 200
413 or "http_method" in resp
414 and resp["http_method"] == "DELETE"
415 and resp["http_status"] == 404
416 )
417
418
419 def fortios_system(data, fos, check_mode):
420
421 if data["system_evpn"]:
422 resp = system_evpn(data, fos, check_mode)
423 else:
424 fos._module.fail_json(msg="missing task body: %s" % ("system_evpn"))
425 if isinstance(resp, tuple) and len(resp) == 4:
426 return resp
427 return (
428 not is_successful_status(resp),
429 is_successful_status(resp)
430 and (resp["revision_changed"] if "revision_changed" in resp else True),
431 resp,
432 {},
433 )
434
435
436 versioned_schema = {
437 "type": "list",
438 "elements": "dict",
439 "children": {
440 "id": {"v_range": [["v7.4.0", ""]], "type": "integer", "required": True},
441 "rd": {"v_range": [["v7.4.0", ""]], "type": "string"},
442 "import_rt": {
443 "type": "list",
444 "elements": "dict",
445 "children": {
446 "route_target": {
447 "v_range": [["v7.4.0", ""]],
448 "type": "string",
449 "required": True,
450 }
451 },
452 "v_range": [["v7.4.0", ""]],
453 },
454 "export_rt": {
455 "type": "list",
456 "elements": "dict",
457 "children": {
458 "route_target": {
459 "v_range": [["v7.4.0", ""]],
460 "type": "string",
461 "required": True,
462 }
463 },
464 "v_range": [["v7.4.0", ""]],
465 },
466 "ip_local_learning": {
467 "v_range": [["v7.4.0", ""]],
468 "type": "string",
469 "options": [{"value": "enable"}, {"value": "disable"}],
470 },
471 "arp_suppression": {
472 "v_range": [["v7.4.0", ""]],
473 "type": "string",
474 "options": [{"value": "enable"}, {"value": "disable"}],
475 },
476 },
477 "v_range": [["v7.4.0", ""]],
478 }
479
480
481 def main():
482 module_spec = schema_to_module_spec(versioned_schema)
483 mkeyname = "id"
484 fields = {
485 "access_token": {"required": False, "type": "str", "no_log": True},
486 "enable_log": {"required": False, "type": "bool", "default": False},
487 "vdom": {"required": False, "type": "str", "default": "root"},
488 "member_path": {"required": False, "type": "str"},
489 "member_state": {
490 "type": "str",
491 "required": False,
492 "choices": ["present", "absent"],
493 },
494 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
495 "system_evpn": {
496 "required": False,
497 "type": "dict",
498 "default": None,
499 "options": {},
500 },
501 }
502 for attribute_name in module_spec["options"]:
503 fields["system_evpn"]["options"][attribute_name] = module_spec["options"][
504 attribute_name
505 ]
506 if mkeyname and mkeyname == attribute_name:
507 fields["system_evpn"]["options"][attribute_name]["required"] = True
508
509 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
510 check_legacy_fortiosapi(module)
511
512 is_error = False
513 has_changed = False
514 result = None
515 diff = None
516
517 versions_check_result = None
518 if module._socket_path:
519 connection = Connection(module._socket_path)
520 if "access_token" in module.params:
521 connection.set_custom_option("access_token", module.params["access_token"])
522
523 if "enable_log" in module.params:
524 connection.set_custom_option("enable_log", module.params["enable_log"])
525 else:
526 connection.set_custom_option("enable_log", False)
527 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
528 versions_check_result = check_schema_versioning(
529 fos, versioned_schema, "system_evpn"
530 )
531
532 is_error, has_changed, result, diff = fortios_system(
533 module.params, fos, module.check_mode
534 )
535
536 else:
537 module.fail_json(**FAIL_SOCKET_MSG)
538
539 if versions_check_result and versions_check_result["matched"] is False:
540 module.warn(
541 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
542 )
543
544 if not is_error:
545 if versions_check_result and versions_check_result["matched"] is False:
546 module.exit_json(
547 changed=has_changed,
548 version_check_warning=versions_check_result,
549 meta=result,
550 diff=diff,
551 )
552 else:
553 module.exit_json(changed=has_changed, meta=result, diff=diff)
554 else:
555 if versions_check_result and versions_check_result["matched"] is False:
556 module.fail_json(
557 msg="Error in repo",
558 version_check_warning=versions_check_result,
559 meta=result,
560 )
561 else:
562 module.fail_json(msg="Error in repo", meta=result)
563
564
565 if __name__ == "__main__":
566 main()