Debian Codegraph @

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