Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_dlp_label.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_label
23 short_description: Configure labels used by DLP blocking 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 dlp feature and label 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
41 requirements:
42 - ansible>=2.16
43 options:
44 access_token:
45 description:
46 - Token-based authentication.
47 Generated from GUI of Fortigate.
48 type: str
49 required: false
50 enable_log:
51 description:
52 - Enable/Disable logging for task.
53 type: bool
54 required: false
55 default: false
56 vdom:
57 description:
58 - Virtual domain, among those defined previously. A vdom is a
59 virtual instance of the FortiGate that can be configured and
60 used as a different unit.
61 type: str
62 default: root
63 member_path:
64 type: str
65 description:
66 - Member attribute path to operate on.
67 - Delimited by a slash character if there are more than one attribute.
68 - Parameter marked with member_path is legitimate for doing member operation.
69 member_state:
70 type: str
71 description:
72 - Add or delete a member under specified attribute path.
73 - When member_state is specified, the state option is ignored.
74 choices:
75 - 'present'
76 - 'absent'
77
78 state:
79 description:
80 - Indicates whether to create or remove the object.
81 type: str
82 required: true
83 choices:
84 - 'present'
85 - 'absent'
86 dlp_label:
87 description:
88 - Configure labels used by DLP blocking.
89 default: null
90 type: dict
91 suboptions:
92 comment:
93 description:
94 - Optional comments.
95 type: str
96 connector:
97 description:
98 - Name of SDN connector. Source system.sdn-connector.name.
99 type: str
100 entries:
101 description:
102 - DLP label entries.
103 type: list
104 elements: dict
105 suboptions:
106 fortidata_label_name:
107 description:
108 - Name of FortiData label Source dlp.fdata-label.name.
109 type: str
110 guid:
111 description:
112 - MPIP label guid.
113 type: str
114 id:
115 description:
116 - ID. see <a href='#notes'>Notes</a>.
117 required: true
118 type: int
119 mpip_label_name:
120 description:
121 - Name of MPIP label. Source dlp.mpip-label.name.
122 type: str
123 mpip_type:
124 description:
125 - MPIP label type.
126 type: str
127 choices:
128 - 'remote'
129 - 'local'
130 name:
131 description:
132 - Name of table containing the label.
133 required: true
134 type: str
135 type:
136 description:
137 - Label type.
138 type: str
139 choices:
140 - 'mpip'
141 - 'fortidata'
142 """
143
144 EXAMPLES = """
145 - name: Configure labels used by DLP blocking.
146 fortinet.fortios.fortios_dlp_label:
147 vdom: "{{ vdom }}"
148 state: "present"
149 access_token: "<your_own_value>"
150 dlp_label:
151 comment: "Optional comments."
152 connector: "<your_own_value> (source system.sdn-connector.name)"
153 entries:
154 -
155 fortidata_label_name: "<your_own_value> (source dlp.fdata-label.name)"
156 guid: "<your_own_value>"
157 id: "8"
158 mpip_label_name: "<your_own_value> (source dlp.mpip-label.name)"
159 mpip_type: "remote"
160 name: "default_name_11"
161 type: "mpip"
162 """
163
164 RETURN = """
165 build:
166 description: Build number of the fortigate image
167 returned: always
168 type: str
169 sample: '1547'
170 http_method:
171 description: Last method used to provision the content into FortiGate
172 returned: always
173 type: str
174 sample: 'PUT'
175 http_status:
176 description: Last result given by FortiGate on last operation applied
177 returned: always
178 type: str
179 sample: "200"
180 mkey:
181 description: Master key (id) used in the last call to FortiGate
182 returned: success
183 type: str
184 sample: "id"
185 name:
186 description: Name of the table used to fulfill the request
187 returned: always
188 type: str
189 sample: "urlfilter"
190 path:
191 description: Path of the table used to fulfill the request
192 returned: always
193 type: str
194 sample: "webfilter"
195 revision:
196 description: Internal revision number
197 returned: always
198 type: str
199 sample: "17.0.2.10658"
200 serial:
201 description: Serial number of the unit
202 returned: always
203 type: str
204 sample: "FGVMEVYYQT3AB5352"
205 status:
206 description: Indication of the operation's result
207 returned: always
208 type: str
209 sample: "success"
210 vdom:
211 description: Virtual domain used
212 returned: always
213 type: str
214 sample: "root"
215 version:
216 description: Version of the FortiGate
217 returned: always
218 type: str
219 sample: "v5.6.3"
220 """
221 from ansible.module_utils.basic import AnsibleModule
222 from ansible.module_utils.connection import Connection
223 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
224 FortiOSHandler,
225 )
226 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
227 check_legacy_fortiosapi,
228 )
229 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
230 schema_to_module_spec,
231 )
232 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
233 check_schema_versioning,
234 )
235 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
236 FAIL_SOCKET_MSG,
237 )
238 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
239 remove_invalid_fields,
240 )
241
242
243 def filter_dlp_label_data(json):
244 option_list = ["comment", "connector", "entries", "mpip_type", "name", "type"]
245
246 json = remove_invalid_fields(json)
247 dictionary = {}
248
249 for attribute in option_list:
250 if attribute in json and json[attribute] is not None:
251 dictionary[attribute] = json[attribute]
252
253 return dictionary
254
255
256 def underscore_to_hyphen(data):
257 new_data = None
258 if isinstance(data, list):
259 new_data = []
260 for i, elem in enumerate(data):
261 new_data.append(underscore_to_hyphen(elem))
262 elif isinstance(data, dict):
263 new_data = {}
264 for k, v in data.items():
265 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
266 else:
267 return data
268 return new_data
269
270
271 def dlp_label(data, fos):
272 state = None
273 vdom = data["vdom"]
274 parameters = None
275 state = data.get("state", None)
276 dlp_label_data = data["dlp_label"]
277
278 filtered_data = filter_dlp_label_data(dlp_label_data)
279 converted_data = underscore_to_hyphen(filtered_data)
280
281 # pass post processed data to member operations
282 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
283 data_copy = data.copy()
284 data_copy["dlp_label"] = filtered_data
285 fos.do_member_operation(
286 "dlp",
287 "label",
288 data_copy,
289 )
290
291 if state == "present" or state is True:
292 return fos.set(
293 "dlp", "label", data=converted_data, vdom=vdom, parameters=parameters
294 )
295
296 elif state == "absent":
297 return fos.delete(
298 "dlp",
299 "label",
300 mkey=converted_data["name"],
301 vdom=vdom,
302 parameters=parameters,
303 )
304 else:
305 fos._module.fail_json(msg="state must be present or absent!")
306
307
308 def is_successful_status(resp):
309 return (
310 "status" in resp
311 and resp["status"] == "success"
312 or "http_status" in resp
313 and resp["http_status"] == 200
314 or "http_method" in resp
315 and resp["http_method"] == "DELETE"
316 and resp["http_status"] == 404
317 )
318
319
320 def fortios_dlp(data, fos):
321
322 if data["dlp_label"]:
323 resp = dlp_label(data, fos)
324 else:
325 fos._module.fail_json(msg="missing task body: %s" % ("dlp_label"))
326
327 return (
328 not is_successful_status(resp),
329 is_successful_status(resp)
330 and (resp["revision_changed"] if "revision_changed" in resp else True),
331 resp,
332 {},
333 )
334
335
336 versioned_schema = {
337 "type": "list",
338 "elements": "dict",
339 "children": {
340 "name": {"v_range": [["v7.6.3", ""]], "type": "string", "required": True},
341 "type": {
342 "v_range": [["v7.6.3", ""]],
343 "type": "string",
344 "options": [
345 {"value": "mpip"},
346 {"value": "fortidata", "v_range": [["v7.6.4", ""]]},
347 ],
348 },
349 "mpip_type": {
350 "v_range": [["v7.6.3", ""]],
351 "type": "string",
352 "options": [{"value": "remote"}, {"value": "local"}],
353 },
354 "connector": {"v_range": [["v7.6.3", ""]], "type": "string"},
355 "comment": {"v_range": [["v7.6.3", ""]], "type": "string"},
356 "entries": {
357 "type": "list",
358 "elements": "dict",
359 "children": {
360 "id": {
361 "v_range": [["v7.6.3", ""]],
362 "type": "integer",
363 "required": True,
364 },
365 "fortidata_label_name": {"v_range": [["v7.6.4", ""]], "type": "string"},
366 "mpip_label_name": {"v_range": [["v7.6.3", ""]], "type": "string"},
367 "guid": {"v_range": [["v7.6.3", ""]], "type": "string"},
368 },
369 "v_range": [["v7.6.3", ""]],
370 },
371 },
372 "v_range": [["v7.6.3", ""]],
373 }
374
375
376 def main():
377 module_spec = schema_to_module_spec(versioned_schema)
378 mkeyname = "name"
379 fields = {
380 "access_token": {"required": False, "type": "str", "no_log": True},
381 "enable_log": {"required": False, "type": "bool", "default": False},
382 "vdom": {"required": False, "type": "str", "default": "root"},
383 "member_path": {"required": False, "type": "str"},
384 "member_state": {
385 "type": "str",
386 "required": False,
387 "choices": ["present", "absent"],
388 },
389 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
390 "dlp_label": {
391 "required": False,
392 "type": "dict",
393 "default": None,
394 "options": {},
395 },
396 }
397 for attribute_name in module_spec["options"]:
398 fields["dlp_label"]["options"][attribute_name] = module_spec["options"][
399 attribute_name
400 ]
401 if mkeyname and mkeyname == attribute_name:
402 fields["dlp_label"]["options"][attribute_name]["required"] = True
403
404 module = AnsibleModule(argument_spec=fields, supports_check_mode=False)
405 check_legacy_fortiosapi(module)
406
407 is_error = False
408 has_changed = False
409 result = None
410 diff = None
411
412 versions_check_result = None
413 if module._socket_path:
414 connection = Connection(module._socket_path)
415 if "access_token" in module.params:
416 connection.set_custom_option("access_token", module.params["access_token"])
417
418 if "enable_log" in module.params:
419 connection.set_custom_option("enable_log", module.params["enable_log"])
420 else:
421 connection.set_custom_option("enable_log", False)
422 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
423 versions_check_result = check_schema_versioning(
424 fos, versioned_schema, "dlp_label"
425 )
426
427 is_error, has_changed, result, diff = fortios_dlp(module.params, fos)
428
429 else:
430 module.fail_json(**FAIL_SOCKET_MSG)
431
432 if versions_check_result and versions_check_result["matched"] is False:
433 module.warn(
434 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
435 )
436
437 if not is_error:
438 if versions_check_result and versions_check_result["matched"] is False:
439 module.exit_json(
440 changed=has_changed,
441 version_check_warning=versions_check_result,
442 meta=result,
443 diff=diff,
444 )
445 else:
446 module.exit_json(changed=has_changed, meta=result, diff=diff)
447 else:
448 if versions_check_result and versions_check_result["matched"] is False:
449 module.fail_json(
450 msg="Error in repo",
451 version_check_warning=versions_check_result,
452 meta=result,
453 )
454 else:
455 module.fail_json(msg="Error in repo", meta=result)
456
457
458 if __name__ == "__main__":
459 main()