Debian Codegraph @

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