Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_firewall_vipgrp46.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_vipgrp46
23 short_description: Configure IPv4 to 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 vipgrp46 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_vipgrp46:
88 description:
89 - Configure IPv4 to 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 - VIP46 name. Source firewall.vip46.name.
110 required: true
111 type: str
112 name:
113 description:
114 - VIP46 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 IPv4 to IPv6 virtual IP groups.
125 fortinet.fortios.fortios_firewall_vipgrp46:
126 vdom: "{{ vdom }}"
127 state: "present"
128 access_token: "<your_own_value>"
129 firewall_vipgrp46:
130 color: "0"
131 comments: "<your_own_value>"
132 member:
133 -
134 name: "default_name_6 (source firewall.vip46.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_vipgrp46_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_vipgrp46(data, fos, check_mode=False):
259
260 state = None
261 vdom = data["vdom"]
262 parameters = None
263 state = data.get("state", None)
264 firewall_vipgrp46_data = data["firewall_vipgrp46"]
265
266 filtered_data = filter_firewall_vipgrp46_data(firewall_vipgrp46_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", "vipgrp46", filtered_data, vdom=vdom)
277 current_data = fos.get(
278 "firewall", "vipgrp46", 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_vipgrp46"] = filtered_data
355 fos.do_member_operation(
356 "firewall",
357 "vipgrp46",
358 data_copy,
359 )
360
361 if state == "present" or state is True:
362 return fos.set(
363 "firewall",
364 "vipgrp46",
365 data=converted_data,
366 vdom=vdom,
367 parameters=parameters,
368 )
369
370 elif state == "absent":
371 return fos.delete(
372 "firewall",
373 "vipgrp46",
374 mkey=converted_data["name"],
375 vdom=vdom,
376 parameters=parameters,
377 )
378 else:
379 fos._module.fail_json(msg="state must be present or absent!")
380
381
382 def is_successful_status(resp):
383 return (
384 "status" in resp
385 and resp["status"] == "success"
386 or "http_status" in resp
387 and resp["http_status"] == 200
388 or "http_method" in resp
389 and resp["http_method"] == "DELETE"
390 and resp["http_status"] == 404
391 )
392
393
394 def fortios_firewall(data, fos, check_mode):
395
396 if data["firewall_vipgrp46"]:
397 resp = firewall_vipgrp46(data, fos, check_mode)
398 else:
399 fos._module.fail_json(msg="missing task body: %s" % ("firewall_vipgrp46"))
400 if isinstance(resp, tuple) and len(resp) == 4:
401 return resp
402 return (
403 not is_successful_status(resp),
404 is_successful_status(resp)
405 and (resp["revision_changed"] if "revision_changed" in resp else True),
406 resp,
407 {},
408 )
409
410
411 versioned_schema = {
412 "type": "list",
413 "elements": "dict",
414 "children": {
415 "name": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string", "required": True},
416 "uuid": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
417 "color": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "integer"},
418 "comments": {"v_range": [["v6.0.0", "v7.0.0"]], "type": "string"},
419 "member": {
420 "type": "list",
421 "elements": "dict",
422 "children": {
423 "name": {
424 "v_range": [["v6.0.0", "v7.0.0"]],
425 "type": "string",
426 "required": True,
427 }
428 },
429 "v_range": [["v6.0.0", "v7.0.0"]],
430 },
431 },
432 "v_range": [["v6.0.0", "v7.0.0"]],
433 }
434
435
436 def main():
437 module_spec = schema_to_module_spec(versioned_schema)
438 mkeyname = "name"
439 fields = {
440 "access_token": {"required": False, "type": "str", "no_log": True},
441 "enable_log": {"required": False, "type": "bool", "default": False},
442 "vdom": {"required": False, "type": "str", "default": "root"},
443 "member_path": {"required": False, "type": "str"},
444 "member_state": {
445 "type": "str",
446 "required": False,
447 "choices": ["present", "absent"],
448 },
449 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
450 "firewall_vipgrp46": {
451 "required": False,
452 "type": "dict",
453 "default": None,
454 "options": {},
455 },
456 }
457 for attribute_name in module_spec["options"]:
458 fields["firewall_vipgrp46"]["options"][attribute_name] = module_spec["options"][
459 attribute_name
460 ]
461 if mkeyname and mkeyname == attribute_name:
462 fields["firewall_vipgrp46"]["options"][attribute_name]["required"] = True
463
464 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
465 check_legacy_fortiosapi(module)
466
467 is_error = False
468 has_changed = False
469 result = None
470 diff = None
471
472 versions_check_result = None
473 if module._socket_path:
474 connection = Connection(module._socket_path)
475 if "access_token" in module.params:
476 connection.set_custom_option("access_token", module.params["access_token"])
477
478 if "enable_log" in module.params:
479 connection.set_custom_option("enable_log", module.params["enable_log"])
480 else:
481 connection.set_custom_option("enable_log", False)
482 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
483 versions_check_result = check_schema_versioning(
484 fos, versioned_schema, "firewall_vipgrp46"
485 )
486
487 is_error, has_changed, result, diff = fortios_firewall(
488 module.params, fos, module.check_mode
489 )
490
491 else:
492 module.fail_json(**FAIL_SOCKET_MSG)
493
494 if versions_check_result and versions_check_result["matched"] is False:
495 module.warn(
496 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
497 )
498
499 if not is_error:
500 if versions_check_result and versions_check_result["matched"] is False:
501 module.exit_json(
502 changed=has_changed,
503 version_check_warning=versions_check_result,
504 meta=result,
505 diff=diff,
506 )
507 else:
508 module.exit_json(changed=has_changed, meta=result, diff=diff)
509 else:
510 if versions_check_result and versions_check_result["matched"] is False:
511 module.fail_json(
512 msg="Error in repo",
513 version_check_warning=versions_check_result,
514 meta=result,
515 )
516 else:
517 module.fail_json(msg="Error in repo", meta=result)
518
519
520 if __name__ == "__main__":
521 main()