Debian Codegraph @

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