Debian Codegraph @

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