Debian Codegraph @

ansible_collections/community/general/plugins/modules/vertica_configuration.py

raw
1 #!/usr/bin/python
2 # Copyright Ansible Project
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 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: vertica_configuration
10 short_description: Updates Vertica configuration parameters
11 description:
12 - Updates Vertica configuration parameters.
13 extends_documentation_fragment:
14 - community.general._attributes
15 attributes:
16 check_mode:
17 support: full
18 diff_mode:
19 support: none
20 options:
21 parameter:
22 description:
23 - Name of the parameter to update.
24 required: true
25 aliases: [name]
26 type: str
27 value:
28 description:
29 - Value of the parameter to be set.
30 type: str
31 db:
32 description:
33 - Name of the Vertica database.
34 type: str
35 cluster:
36 description:
37 - Name of the Vertica cluster.
38 default: localhost
39 type: str
40 port:
41 description:
42 - Vertica cluster port to connect to.
43 default: '5433'
44 type: str
45 login_user:
46 description:
47 - The username used to authenticate with.
48 default: dbadmin
49 type: str
50 login_password:
51 description:
52 - The password used to authenticate with.
53 type: str
54 notes:
55 - The default authentication assumes that you are either logging in as or sudo'ing to the C(dbadmin) account on the host.
56 - This module uses C(pyodbc), a Python ODBC database adapter. You must ensure that C(unixODBC) and C(pyodbc) is installed
57 on the host and properly configured.
58 - Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so) to be added to the C(Vertica)
59 section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini) and both C(ErrorMessagesPath = /opt/vertica/lib64) and
60 C(DriverManagerEncoding = UTF-16) to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini).
61 requirements: ['unixODBC', 'pyodbc']
62 author: "Dariusz Owczarek (@dareko)"
63 """
64
65 EXAMPLES = r"""
66 - name: Updating load_balance_policy
67 community.general.vertica_configuration: name=failovertostandbyafter value='8 hours'
68 """
69 import traceback
70
71 PYODBC_IMP_ERR = None
72 try:
73 import pyodbc
74 except ImportError:
75 PYODBC_IMP_ERR = traceback.format_exc()
76 pyodbc_found = False
77 else:
78 pyodbc_found = True
79
80 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
81
82
83 class NotSupportedError(Exception):
84 pass
85
86
87 class CannotDropError(Exception):
88 pass
89
90
91 # module specific functions
92
93
94 def get_configuration_facts(cursor, parameter_name=""):
95 facts = {}
96 cursor.execute(
97 """
98 select c.parameter_name, c.current_value, c.default_value
99 from configuration_parameters c
100 where c.node_name = 'ALL'
101 and (? = '' or c.parameter_name ilike ?)
102 """,
103 parameter_name,
104 parameter_name,
105 )
106 while True:
107 rows = cursor.fetchmany(100)
108 if not rows:
109 break
110 for row in rows:
111 facts[row.parameter_name.lower()] = {
112 "parameter_name": row.parameter_name,
113 "current_value": row.current_value,
114 "default_value": row.default_value,
115 }
116 return facts
117
118
119 def check(configuration_facts, parameter_name, current_value):
120 parameter_key = parameter_name.lower()
121 return not (current_value and current_value.lower() != configuration_facts[parameter_key]["current_value"].lower())
122
123
124 def present(configuration_facts, cursor, parameter_name, current_value):
125 parameter_key = parameter_name.lower()
126 changed = False
127 if current_value and current_value.lower() != configuration_facts[parameter_key]["current_value"].lower():
128 cursor.execute(f"select set_config_parameter('{parameter_name}', '{current_value}')")
129 changed = True
130 if changed:
131 configuration_facts.update(get_configuration_facts(cursor, parameter_name))
132 return changed
133
134
135 # module logic
136
137
138 def main():
139 module = AnsibleModule(
140 argument_spec=dict(
141 parameter=dict(required=True, aliases=["name"]),
142 value=dict(),
143 db=dict(),
144 cluster=dict(default="localhost"),
145 port=dict(default="5433"),
146 login_user=dict(default="dbadmin"),
147 login_password=dict(no_log=True),
148 ),
149 supports_check_mode=True,
150 )
151
152 if not pyodbc_found:
153 module.fail_json(msg=missing_required_lib("pyodbc"), exception=PYODBC_IMP_ERR)
154
155 parameter_name = module.params["parameter"]
156 current_value = module.params["value"]
157 db = ""
158 if module.params["db"]:
159 db = module.params["db"]
160
161 changed = False
162
163 try:
164 dsn = (
165 "Driver=Vertica;"
166 f"Server={module.params['cluster']};"
167 f"Port={module.params['port']};"
168 f"Database={db};"
169 f"User={module.params['login_user']};"
170 f"Password={module.params['login_password']};"
171 f"ConnectionLoadBalance=true"
172 )
173 db_conn = pyodbc.connect(dsn, autocommit=True)
174 cursor = db_conn.cursor()
175 except Exception as e:
176 module.fail_json(msg=f"Unable to connect to database: {e}.", exception=traceback.format_exc())
177
178 try:
179 configuration_facts = get_configuration_facts(cursor)
180 if module.check_mode:
181 changed = not check(configuration_facts, parameter_name, current_value)
182 else:
183 try:
184 changed = present(configuration_facts, cursor, parameter_name, current_value)
185 except pyodbc.Error as e:
186 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
187 except NotSupportedError as e:
188 module.fail_json(msg=f"{e}", ansible_facts={"vertica_configuration": configuration_facts})
189 except CannotDropError as e:
190 module.fail_json(msg=f"{e}", ansible_facts={"vertica_configuration": configuration_facts})
191 except SystemExit:
192 # avoid catching this on python 2.4
193 raise
194 except Exception as e:
195 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
196
197 module.exit_json(
198 changed=changed, parameter=parameter_name, ansible_facts={"vertica_configuration": configuration_facts}
199 )
200
201
202 if __name__ == "__main__":
203 main()