Debian Codegraph @

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