Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_lxca_common.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by
4 # Ansible still belong to the author of the module, and may assign their
5 # own license to the complete work.
6 #
7 # Copyright (C) 2017 Lenovo, Inc.
8 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
9 # SPDX-License-Identifier: BSD-2-Clause
10 #
11 # Contains LXCA common class
12 # Lenovo xClarity Administrator (LXCA)
13
14 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
15 # Do not use this from other collections or standalone plugins/modules!
16
17 from __future__ import annotations
18
19 import traceback
20 import typing as t
21
22 try:
23 from pylxca import connect, disconnect
24
25 HAS_PYLXCA = True
26 except ImportError:
27 HAS_PYLXCA = False
28
29 if t.TYPE_CHECKING:
30 from ansible.module_utils.basic import AnsibleModule
31
32
33 PYLXCA_REQUIRED = "Lenovo xClarity Administrator Python Client (Python package 'pylxca') is required for this module."
34
35
36 def has_pylxca(module: AnsibleModule) -> None:
37 """
38 Check pylxca is installed
39 :param module:
40 """
41 if not HAS_PYLXCA:
42 module.fail_json(msg=PYLXCA_REQUIRED)
43
44
45 LXCA_COMMON_ARGS = dict(
46 login_user=dict(required=True),
47 login_password=dict(required=True, no_log=True),
48 auth_url=dict(required=True),
49 )
50
51
52 class connection_object:
53 def __init__(self, module: AnsibleModule) -> None:
54 self.module = module
55
56 def __enter__(self):
57 return setup_conn(self.module)
58
59 def __exit__(self, type, value, traceback) -> None:
60 close_conn()
61
62
63 def setup_conn(module: AnsibleModule):
64 """
65 this function create connection to LXCA
66 :param module:
67 :return: lxca connection
68 """
69 lxca_con = None
70 try:
71 lxca_con = connect(
72 module.params["auth_url"], module.params["login_user"], module.params["login_password"], "True"
73 )
74 except Exception as exception:
75 error_msg = "; ".join(exception.args)
76 module.fail_json(msg=error_msg, exception=traceback.format_exc())
77 return lxca_con
78
79
80 def close_conn() -> None:
81 """
82 this function close connection to LXCA
83 :param module:
84 :return: None
85 """
86 disconnect()