Debian Codegraph @

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