Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_system_zone.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_system_zone
23 short_description: Configure zones to group two or more interfaces. When a zone is created you can configure policies for the zone instead of individual
24 interfaces in the zone in Fortinet's FortiOS and FortiGate.
25 description:
26 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
27 user to set and modify system feature and zone category.
28 Examples include all parameters and values need to be adjusted to datasources before usage.
29 Tested with FOS v6.0.0
30 version_added: "2.0.0"
31 author:
32 - Link Zheng (@chillancezen)
33 - Jie Xue (@JieX19)
34 - Hongbin Lu (@fgtdev-hblu)
35 - Frank Shen (@frankshen01)
36 - Miguel Angel Munoz (@mamunozgonzalez)
37 - Nicolas Thomas (@thomnico)
38 notes:
39 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
40
41 - The module supports check_mode.
42
43 requirements:
44 - ansible>=2.16
45 options:
46 access_token:
47 description:
48 - Token-based authentication.
49 Generated from GUI of Fortigate.
50 type: str
51 required: false
52 enable_log:
53 description:
54 - Enable/Disable logging for task.
55 type: bool
56 required: false
57 default: false
58 vdom:
59 description:
60 - Virtual domain, among those defined previously. A vdom is a
61 virtual instance of the FortiGate that can be configured and
62 used as a different unit.
63 type: str
64 default: root
65 member_path:
66 type: str
67 description:
68 - Member attribute path to operate on.
69 - Delimited by a slash character if there are more than one attribute.
70 - Parameter marked with member_path is legitimate for doing member operation.
71 member_state:
72 type: str
73 description:
74 - Add or delete a member under specified attribute path.
75 - When member_state is specified, the state option is ignored.
76 choices:
77 - 'present'
78 - 'absent'
79
80 state:
81 description:
82 - Indicates whether to create or remove the object.
83 type: str
84 required: true
85 choices:
86 - 'present'
87 - 'absent'
88 system_zone:
89 description:
90 - Configure zones to group two or more interfaces. When a zone is created you can configure policies for the zone instead of individual interfaces
91 in the zone.
92 default: null
93 type: dict
94 suboptions:
95 description:
96 description:
97 - Description.
98 type: str
99 interface:
100 description:
101 - Add interfaces to this zone. Interfaces must not be assigned to another zone or have firewall policies defined.
102 type: list
103 elements: dict
104 suboptions:
105 interface_name:
106 description:
107 - Select interfaces to add to the zone. Source system.interface.name.
108 required: true
109 type: str
110 intrazone:
111 description:
112 - Allow or deny traffic routing between different interfaces in the same zone .
113 type: str
114 choices:
115 - 'allow'
116 - 'deny'
117 name:
118 description:
119 - Zone name.
120 required: true
121 type: str
122 tagging:
123 description:
124 - Config object tagging.
125 type: list
126 elements: dict
127 suboptions:
128 category:
129 description:
130 - Tag category. Source system.object-tagging.category.
131 type: str
132 name:
133 description:
134 - Tagging entry name.
135 required: true
136 type: str
137 tags:
138 description:
139 - Tags.
140 type: list
141 elements: dict
142 suboptions:
143 name:
144 description:
145 - Tag name. Source system.object-tagging.tags.name.
146 required: true
147 type: str
148 """
149
150 EXAMPLES = """
151 - name: Configure zones to group two or more interfaces. When a zone is created you can configure policies for the zone instead of individual interfaces in
152 the zone.
153 fortinet.fortios.fortios_system_zone:
154 vdom: "{{ vdom }}"
155 state: "present"
156 access_token: "<your_own_value>"
157 system_zone:
158 description: "<your_own_value>"
159 interface:
160 -
161 interface_name: "<your_own_value> (source system.interface.name)"
162 intrazone: "allow"
163 name: "default_name_7"
164 tagging:
165 -
166 category: "<your_own_value> (source system.object-tagging.category)"
167 name: "default_name_10"
168 tags:
169 -
170 name: "default_name_12 (source system.object-tagging.tags.name)"
171 """
172
173 RETURN = """
174 build:
175 description: Build number of the fortigate image
176 returned: always
177 type: str
178 sample: '1547'
179 http_method:
180 description: Last method used to provision the content into FortiGate
181 returned: always
182 type: str
183 sample: 'PUT'
184 http_status:
185 description: Last result given by FortiGate on last operation applied
186 returned: always
187 type: str
188 sample: "200"
189 mkey:
190 description: Master key (id) used in the last call to FortiGate
191 returned: success
192 type: str
193 sample: "id"
194 name:
195 description: Name of the table used to fulfill the request
196 returned: always
197 type: str
198 sample: "urlfilter"
199 path:
200 description: Path of the table used to fulfill the request
201 returned: always
202 type: str
203 sample: "webfilter"
204 revision:
205 description: Internal revision number
206 returned: always
207 type: str
208 sample: "17.0.2.10658"
209 serial:
210 description: Serial number of the unit
211 returned: always
212 type: str
213 sample: "FGVMEVYYQT3AB5352"
214 status:
215 description: Indication of the operation's result
216 returned: always
217 type: str
218 sample: "success"
219 vdom:
220 description: Virtual domain used
221 returned: always
222 type: str
223 sample: "root"
224 version:
225 description: Version of the FortiGate
226 returned: always
227 type: str
228 sample: "v5.6.3"
229 """
230 from ansible.module_utils.basic import AnsibleModule
231 from ansible.module_utils.connection import Connection
232 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
233 FortiOSHandler,
234 )
235 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
236 check_legacy_fortiosapi,
237 )
238 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
239 schema_to_module_spec,
240 )
241 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
242 check_schema_versioning,
243 )
244 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
245 FAIL_SOCKET_MSG,
246 )
247 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
248 remove_invalid_fields,
249 )
250 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
251 is_same_comparison,
252 )
253 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
254 serialize,
255 )
256 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
257 find_current_values,
258 )
259 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
260 unify_data_format,
261 )
262
263
264 def filter_system_zone_data(json):
265 option_list = ["description", "interface", "intrazone", "name", "tagging"]
266
267 json = remove_invalid_fields(json)
268 dictionary = {}
269
270 for attribute in option_list:
271 if attribute in json and json[attribute] is not None:
272 dictionary[attribute] = json[attribute]
273
274 return dictionary
275
276
277 def underscore_to_hyphen(data):
278 new_data = None
279 if isinstance(data, list):
280 new_data = []
281 for i, elem in enumerate(data):
282 new_data.append(underscore_to_hyphen(elem))
283 elif isinstance(data, dict):
284 new_data = {}
285 for k, v in data.items():
286 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
287 else:
288 return data
289 return new_data
290
291
292 def system_zone(data, fos, check_mode=False):
293
294 state = None
295 vdom = data["vdom"]
296 parameters = None
297 state = data.get("state", None)
298 system_zone_data = data["system_zone"]
299
300 filtered_data = filter_system_zone_data(system_zone_data)
301 converted_data = underscore_to_hyphen(filtered_data)
302
303 # check_mode starts from here
304 if check_mode:
305 diff = {
306 "before": "",
307 "after": filtered_data,
308 }
309 mkeyname = fos.get_mkeyname(None, None)
310 mkey = fos.get_mkey("system", "zone", filtered_data, vdom=vdom)
311 current_data = fos.get(
312 "system", "zone", vdom=vdom, mkey=mkey, parameters=parameters
313 )
314 is_existed = (
315 current_data
316 and current_data.get("http_status") == 200
317 and (
318 mkeyname
319 and isinstance(current_data.get("results"), list)
320 and len(current_data["results"]) > 0
321 or not mkeyname
322 and current_data["results"] # global object response
323 )
324 )
325
326 # 2. if it exists and the state is 'present' then compare current settings with desired
327 if state == "present" or state is True or state is None:
328 # for non global modules, mkeyname must exist and it's a new module when mkey is None
329 if mkeyname is not None and mkey is None:
330 return False, True, filtered_data, diff
331
332 # if mkey exists then compare each other
333 # record exits and they're matched or not
334 copied_filtered_data = filtered_data.copy()
335 copied_filtered_data.pop(mkeyname, None)
336 unified_filtered_data = unify_data_format(copied_filtered_data)
337
338 current_data_results = current_data.get("results", {})
339 current_config = (
340 current_data_results[0]
341 if mkeyname
342 and isinstance(current_data_results, list)
343 and len(current_data_results) > 0
344 else current_data_results
345 )
346 if is_existed:
347 unified_current_values = find_current_values(
348 unified_filtered_data,
349 unify_data_format(current_config),
350 )
351
352 is_same = is_same_comparison(
353 serialize(unified_current_values), serialize(unified_filtered_data)
354 )
355
356 return (
357 False,
358 not is_same,
359 filtered_data,
360 {"before": unified_current_values, "after": unified_filtered_data},
361 )
362
363 # record does not exist
364 return False, True, filtered_data, diff
365
366 if state == "absent":
367 if mkey is None:
368 return (
369 False,
370 False,
371 filtered_data,
372 {"before": current_data["results"][0], "after": ""},
373 )
374
375 if is_existed:
376 return (
377 False,
378 True,
379 filtered_data,
380 {"before": current_data["results"][0], "after": ""},
381 )
382 return False, False, filtered_data, {}
383
384 return True, False, {"reason: ": "Must provide state parameter"}, {}
385 # pass post processed data to member operations
386 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
387 data_copy = data.copy()
388 data_copy["system_zone"] = filtered_data
389 fos.do_member_operation(
390 "system",
391 "zone",
392 data_copy,
393 )
394
395 if state == "present" or state is True:
396 return fos.set(
397 "system", "zone", data=converted_data, vdom=vdom, parameters=parameters
398 )
399
400 elif state == "absent":
401 return fos.delete(
402 "system",
403 "zone",
404 mkey=converted_data["name"],
405 vdom=vdom,
406 parameters=parameters,
407 )
408 else:
409 fos._module.fail_json(msg="state must be present or absent!")
410
411
412 def is_successful_status(resp):
413 return (
414 "status" in resp
415 and resp["status"] == "success"
416 or "http_status" in resp
417 and resp["http_status"] == 200
418 or "http_method" in resp
419 and resp["http_method"] == "DELETE"
420 and resp["http_status"] == 404
421 )
422
423
424 def fortios_system(data, fos, check_mode):
425
426 if data["system_zone"]:
427 resp = system_zone(data, fos, check_mode)
428 else:
429 fos._module.fail_json(msg="missing task body: %s" % ("system_zone"))
430 if isinstance(resp, tuple) and len(resp) == 4:
431 return resp
432 return (
433 not is_successful_status(resp),
434 is_successful_status(resp)
435 and (resp["revision_changed"] if "revision_changed" in resp else True),
436 resp,
437 {},
438 )
439
440
441 versioned_schema = {
442 "type": "list",
443 "elements": "dict",
444 "children": {
445 "name": {"v_range": [["v6.0.0", ""]], "type": "string", "required": True},
446 "tagging": {
447 "type": "list",
448 "elements": "dict",
449 "children": {
450 "name": {
451 "v_range": [["v6.0.0", ""]],
452 "type": "string",
453 "required": True,
454 },
455 "category": {"v_range": [["v6.0.0", ""]], "type": "string"},
456 "tags": {
457 "type": "list",
458 "elements": "dict",
459 "children": {
460 "name": {
461 "v_range": [["v6.0.0", ""]],
462 "type": "string",
463 "required": True,
464 }
465 },
466 "v_range": [["v6.0.0", ""]],
467 },
468 },
469 "v_range": [["v6.0.0", ""]],
470 },
471 "description": {"v_range": [["v6.2.0", ""]], "type": "string"},
472 "intrazone": {
473 "v_range": [["v6.0.0", ""]],
474 "type": "string",
475 "options": [{"value": "allow"}, {"value": "deny"}],
476 },
477 "interface": {
478 "type": "list",
479 "elements": "dict",
480 "children": {
481 "interface_name": {
482 "v_range": [["v6.0.0", ""]],
483 "type": "string",
484 "required": True,
485 }
486 },
487 "v_range": [["v6.0.0", ""]],
488 },
489 },
490 "v_range": [["v6.0.0", ""]],
491 }
492
493
494 def main():
495 module_spec = schema_to_module_spec(versioned_schema)
496 mkeyname = "name"
497 fields = {
498 "access_token": {"required": False, "type": "str", "no_log": True},
499 "enable_log": {"required": False, "type": "bool", "default": False},
500 "vdom": {"required": False, "type": "str", "default": "root"},
501 "member_path": {"required": False, "type": "str"},
502 "member_state": {
503 "type": "str",
504 "required": False,
505 "choices": ["present", "absent"],
506 },
507 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
508 "system_zone": {
509 "required": False,
510 "type": "dict",
511 "default": None,
512 "options": {},
513 },
514 }
515 for attribute_name in module_spec["options"]:
516 fields["system_zone"]["options"][attribute_name] = module_spec["options"][
517 attribute_name
518 ]
519 if mkeyname and mkeyname == attribute_name:
520 fields["system_zone"]["options"][attribute_name]["required"] = True
521
522 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
523 check_legacy_fortiosapi(module)
524
525 is_error = False
526 has_changed = False
527 result = None
528 diff = None
529
530 versions_check_result = None
531 if module._socket_path:
532 connection = Connection(module._socket_path)
533 if "access_token" in module.params:
534 connection.set_custom_option("access_token", module.params["access_token"])
535
536 if "enable_log" in module.params:
537 connection.set_custom_option("enable_log", module.params["enable_log"])
538 else:
539 connection.set_custom_option("enable_log", False)
540 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
541 versions_check_result = check_schema_versioning(
542 fos, versioned_schema, "system_zone"
543 )
544
545 is_error, has_changed, result, diff = fortios_system(
546 module.params, fos, module.check_mode
547 )
548
549 else:
550 module.fail_json(**FAIL_SOCKET_MSG)
551
552 if versions_check_result and versions_check_result["matched"] is False:
553 module.warn(
554 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
555 )
556
557 if not is_error:
558 if versions_check_result and versions_check_result["matched"] is False:
559 module.exit_json(
560 changed=has_changed,
561 version_check_warning=versions_check_result,
562 meta=result,
563 diff=diff,
564 )
565 else:
566 module.exit_json(changed=has_changed, meta=result, diff=diff)
567 else:
568 if versions_check_result and versions_check_result["matched"] is False:
569 module.fail_json(
570 msg="Error in repo",
571 version_check_warning=versions_check_result,
572 meta=result,
573 )
574 else:
575 module.fail_json(msg="Error in repo", meta=result)
576
577
578 if __name__ == "__main__":
579 main()