Debian Codegraph @

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