Debian Codegraph @

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