Debian Codegraph @

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