Debian Codegraph @

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

raw
1 #
2 # Copyright (c) 2021, Andreas Botzner <andreas at botzner dot com>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import traceback
12 import typing as t
13
14 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
15
16 if t.TYPE_CHECKING:
17 from ansible.module_utils.basic import AnsibleModule
18
19 REDIS_IMP_ERR: str | None = None
20 try:
21 from redis import Redis
22 from redis import __version__ as redis_version
23
24 HAS_REDIS_PACKAGE = True
25 REDIS_IMP_ERR = None
26 except ImportError:
27 REDIS_IMP_ERR = traceback.format_exc()
28 HAS_REDIS_PACKAGE = False
29
30 CERTIFI_IMPORT_ERROR: str | None = None
31 try:
32 import certifi
33
34 HAS_CERTIFI_PACKAGE = True
35 except ImportError:
36 CERTIFI_IMPORT_ERROR = traceback.format_exc()
37 HAS_CERTIFI_PACKAGE = False
38
39
40 def fail_imports(module: AnsibleModule, needs_certifi: bool = True) -> None:
41 errors: list[str] = []
42 traceback: list[str] = []
43 if not HAS_REDIS_PACKAGE:
44 errors.append(missing_required_lib("redis"))
45 traceback.append(REDIS_IMP_ERR) # type: ignore
46 if not HAS_CERTIFI_PACKAGE and needs_certifi:
47 errors.append(missing_required_lib("certifi"))
48 traceback.append(CERTIFI_IMPORT_ERROR) # type: ignore
49 if errors:
50 module.fail_json(msg="\n".join(errors), traceback="\n".join(traceback))
51
52
53 def redis_auth_argument_spec(tls_default: bool = True) -> dict[str, t.Any]:
54 return dict(
55 login_host=dict(
56 type="str",
57 default="localhost",
58 ),
59 login_user=dict(type="str"),
60 login_password=dict(type="str", no_log=True),
61 login_port=dict(type="int", default=6379),
62 tls=dict(type="bool", default=tls_default),
63 validate_certs=dict(type="bool", default=True),
64 ca_certs=dict(type="str"),
65 client_cert_file=dict(type="str"),
66 client_key_file=dict(type="str"),
67 )
68
69
70 def redis_auth_params(module: AnsibleModule) -> dict[str, t.Any]:
71 login_host = module.params["login_host"]
72 login_user = module.params["login_user"]
73 login_password = module.params["login_password"]
74 login_port = module.params["login_port"]
75 tls = module.params["tls"]
76 validate_certs = "required" if module.params["validate_certs"] else None
77 ca_certs = module.params["ca_certs"]
78 if tls and ca_certs is None:
79 ca_certs = str(certifi.where())
80 client_cert_file = module.params["client_cert_file"]
81 client_key_file = module.params["client_key_file"]
82 if tuple(map(int, redis_version.split("."))) < (3, 4, 0) and login_user is not None:
83 module.fail_json(msg="The option `username` in only supported with redis >= 3.4.0.")
84 params = {
85 "host": login_host,
86 "port": login_port,
87 "password": login_password,
88 "ssl_ca_certs": ca_certs,
89 "ssl_certfile": client_cert_file,
90 "ssl_keyfile": client_key_file,
91 "ssl_cert_reqs": validate_certs,
92 "ssl": tls,
93 }
94 if login_user is not None:
95 params["username"] = login_user
96 return params
97
98
99 class RedisAnsible:
100 """Base class for Redis module"""
101
102 def __init__(self, module: AnsibleModule) -> None:
103 self.module = module
104 self.connection = self._connect()
105
106 def _connect(self) -> Redis:
107 try:
108 return Redis(**redis_auth_params(self.module))
109 except Exception as e:
110 self.module.fail_json(msg=f"{e}")