Debian Codegraph @

ansible_collections/community/general/plugins/modules/vertica_user.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_user
10 short_description: Adds or removes Vertica database users and assigns roles
11 description:
12 - Adds or removes Vertica database user and, optionally, assigns roles.
13 - A user is not removed until all the dependencies have been dropped.
14 - In such a situation, if the module tries to remove the user it fails and only remove roles granted to the user.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: full
20 diff_mode:
21 support: none
22 options:
23 user:
24 description:
25 - Name of the user to add or remove.
26 required: true
27 type: str
28 aliases: ['name']
29 profile:
30 description:
31 - Sets the user's profile.
32 type: str
33 resource_pool:
34 description:
35 - Sets the user's resource pool.
36 type: str
37 password:
38 description:
39 - The user's password encrypted by the MD5 algorithm.
40 - The password must be generated with the format C("md5" + md5[password + username]), resulting in a total of 35 characters.
41 An easy way to do this is by querying the Vertica database with select V('md5'|| md5('<user_password><user_name>'\)).
42 type: str
43 expired:
44 description:
45 - Sets the user's password expiration.
46 type: bool
47 ldap:
48 description:
49 - Set to V(true) if users are authenticated using LDAP.
50 - The user is created with password expired and set to V($ldap$).
51 type: bool
52 roles:
53 description:
54 - Comma separated list of roles to assign to the user.
55 aliases: ['role']
56 type: str
57 state:
58 description:
59 - Whether to create (V(present)), drop (V(absent)), or lock (V(locked)) a user.
60 choices: ['present', 'absent', 'locked']
61 default: present
62 type: str
63 db:
64 description:
65 - Name of the Vertica database.
66 type: str
67 cluster:
68 description:
69 - Name of the Vertica cluster.
70 default: localhost
71 type: str
72 port:
73 description:
74 - Vertica cluster port to connect to.
75 default: '5433'
76 type: str
77 login_user:
78 description:
79 - The username used to authenticate with.
80 default: dbadmin
81 type: str
82 login_password:
83 description:
84 - The password used to authenticate with.
85 type: str
86 notes:
87 - The default authentication assumes that you are either logging in as or sudo'ing to the C(dbadmin) account on the host.
88 - This module uses C(pyodbc), a Python ODBC database adapter. You must ensure that C(unixODBC) and C(pyodbc) is installed
89 on the host and properly configured.
90 - Configuring C(unixODBC) for Vertica requires C(Driver = /opt/vertica/lib64/libverticaodbc.so) to be added to the C(Vertica)
91 section of either C(/etc/odbcinst.ini) or C($HOME/.odbcinst.ini) and both C(ErrorMessagesPath = /opt/vertica/lib64) and
92 C(DriverManagerEncoding = UTF-16) to be added to the C(Driver) section of either C(/etc/vertica.ini) or C($HOME/.vertica.ini).
93 requirements: ['unixODBC', 'pyodbc']
94 author: "Dariusz Owczarek (@dareko)"
95 """
96
97 EXAMPLES = r"""
98 - name: Creating a new vertica user with password
99 community.general.vertica_user: name=user_name password=md5<encrypted_password> db=db_name state=present
100
101 - name: Creating a new vertica user authenticated via ldap with roles assigned
102 community.general.vertica_user: name=user_name ldap=true db=db_name roles=schema_name_ro state=present
103 """
104 import traceback
105
106 PYODBC_IMP_ERR = None
107 try:
108 import pyodbc
109 except ImportError:
110 PYODBC_IMP_ERR = traceback.format_exc()
111 pyodbc_found = False
112 else:
113 pyodbc_found = True
114
115 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
116
117
118 class NotSupportedError(Exception):
119 pass
120
121
122 class CannotDropError(Exception):
123 pass
124
125
126 # module specific functions
127
128
129 def get_user_facts(cursor, user=""):
130 facts = {}
131 cursor.execute(
132 """
133 select u.user_name, u.is_locked, u.lock_time,
134 p.password, p.acctexpired as is_expired,
135 u.profile_name, u.resource_pool,
136 u.all_roles, u.default_roles
137 from users u join password_auditor p on p.user_id = u.user_id
138 where not u.is_super_user
139 and (? = '' or u.user_name ilike ?)
140 """,
141 user,
142 user,
143 )
144 while True:
145 rows = cursor.fetchmany(100)
146 if not rows:
147 break
148 for row in rows:
149 user_key = row.user_name.lower()
150 facts[user_key] = {
151 "name": row.user_name,
152 "locked": str(row.is_locked),
153 "password": row.password,
154 "expired": str(row.is_expired),
155 "profile": row.profile_name,
156 "resource_pool": row.resource_pool,
157 "roles": [],
158 "default_roles": [],
159 }
160 if row.is_locked:
161 facts[user_key]["locked_time"] = str(row.lock_time)
162 if row.all_roles:
163 facts[user_key]["roles"] = row.all_roles.replace(" ", "").split(",")
164 if row.default_roles:
165 facts[user_key]["default_roles"] = row.default_roles.replace(" ", "").split(",")
166 return facts
167
168
169 def update_roles(user_facts, cursor, user, existing_all, existing_default, required):
170 del_roles = list(set(existing_all) - set(required))
171 if del_roles:
172 cursor.execute(f"revoke {','.join(del_roles)} from {user}")
173 new_roles = list(set(required) - set(existing_all))
174 if new_roles:
175 cursor.execute(f"grant {','.join(new_roles)} to {user}")
176 if required:
177 cursor.execute(f"alter user {user} default role {','.join(required)}")
178
179
180 def check(user_facts, user, profile, resource_pool, locked, password, expired, ldap, roles):
181 user_key = user.lower()
182 if user_key not in user_facts:
183 return False
184 if profile and profile != user_facts[user_key]["profile"]:
185 return False
186 if resource_pool and resource_pool != user_facts[user_key]["resource_pool"]:
187 return False
188 if locked != (user_facts[user_key]["locked"] == "True"):
189 return False
190 if password and password != user_facts[user_key]["password"]:
191 return False
192 if (
193 expired is not None
194 and expired != (user_facts[user_key]["expired"] == "True")
195 or ldap is not None
196 and ldap != (user_facts[user_key]["expired"] == "True")
197 ):
198 return False
199 return not (
200 roles
201 and (
202 sorted(roles) != sorted(user_facts[user_key]["roles"])
203 or sorted(roles) != sorted(user_facts[user_key]["default_roles"])
204 )
205 )
206
207
208 def present(user_facts, cursor, user, profile, resource_pool, locked, password, expired, ldap, roles):
209 user_key = user.lower()
210 if user_key not in user_facts:
211 query_fragments = [f"create user {user}"]
212 if locked:
213 query_fragments.append("account lock")
214 if password or ldap:
215 if password:
216 query_fragments.append(f"identified by '{password}'")
217 else:
218 query_fragments.append("identified by '$ldap$'")
219 if expired or ldap:
220 query_fragments.append("password expire")
221 if profile:
222 query_fragments.append(f"profile {profile}")
223 if resource_pool:
224 query_fragments.append(f"resource pool {resource_pool}")
225 cursor.execute(" ".join(query_fragments))
226 if resource_pool and resource_pool != "general":
227 cursor.execute(f"grant usage on resource pool {resource_pool} to {user}")
228 update_roles(user_facts, cursor, user, [], [], roles)
229 user_facts.update(get_user_facts(cursor, user))
230 return True
231 else:
232 changed = False
233 query_fragments = [f"alter user {user}"]
234 if locked is not None and locked != (user_facts[user_key]["locked"] == "True"):
235 if locked:
236 state = "lock"
237 else:
238 state = "unlock"
239 query_fragments.append(f"account {state}")
240 changed = True
241 if password and password != user_facts[user_key]["password"]:
242 query_fragments.append(f"identified by '{password}'")
243 changed = True
244 if ldap:
245 if ldap != (user_facts[user_key]["expired"] == "True"):
246 query_fragments.append("password expire")
247 changed = True
248 elif expired is not None and expired != (user_facts[user_key]["expired"] == "True"):
249 if expired:
250 query_fragments.append("password expire")
251 changed = True
252 else:
253 raise NotSupportedError("Unexpiring user password is not supported.")
254 if profile and profile != user_facts[user_key]["profile"]:
255 query_fragments.append(f"profile {profile}")
256 changed = True
257 if resource_pool and resource_pool != user_facts[user_key]["resource_pool"]:
258 query_fragments.append(f"resource pool {resource_pool}")
259 if user_facts[user_key]["resource_pool"] != "general":
260 cursor.execute(f"revoke usage on resource pool {user_facts[user_key]['resource_pool']} from {user}")
261 if resource_pool != "general":
262 cursor.execute(f"grant usage on resource pool {resource_pool} to {user}")
263 changed = True
264 if changed:
265 cursor.execute(" ".join(query_fragments))
266 if roles and (
267 sorted(roles) != sorted(user_facts[user_key]["roles"])
268 or sorted(roles) != sorted(user_facts[user_key]["default_roles"])
269 ):
270 update_roles(
271 user_facts, cursor, user, user_facts[user_key]["roles"], user_facts[user_key]["default_roles"], roles
272 )
273 changed = True
274 if changed:
275 user_facts.update(get_user_facts(cursor, user))
276 return changed
277
278
279 def absent(user_facts, cursor, user, roles):
280 user_key = user.lower()
281 if user_key in user_facts:
282 update_roles(user_facts, cursor, user, user_facts[user_key]["roles"], user_facts[user_key]["default_roles"], [])
283 try:
284 cursor.execute(f"drop user {user_facts[user_key]['name']}")
285 except pyodbc.Error as e:
286 raise CannotDropError("Dropping user failed due to dependencies.") from e
287 del user_facts[user_key]
288 return True
289 else:
290 return False
291
292
293 # module logic
294
295
296 def main():
297 module = AnsibleModule(
298 argument_spec=dict(
299 user=dict(required=True, aliases=["name"]),
300 profile=dict(),
301 resource_pool=dict(),
302 password=dict(no_log=True),
303 expired=dict(type="bool"),
304 ldap=dict(type="bool"),
305 roles=dict(aliases=["role"]),
306 state=dict(default="present", choices=["absent", "present", "locked"]),
307 db=dict(),
308 cluster=dict(default="localhost"),
309 port=dict(default="5433"),
310 login_user=dict(default="dbadmin"),
311 login_password=dict(no_log=True),
312 ),
313 supports_check_mode=True,
314 )
315
316 if not pyodbc_found:
317 module.fail_json(msg=missing_required_lib("pyodbc"), exception=PYODBC_IMP_ERR)
318
319 user = module.params["user"]
320 profile = module.params["profile"]
321 if profile:
322 profile = profile.lower()
323 resource_pool = module.params["resource_pool"]
324 if resource_pool:
325 resource_pool = resource_pool.lower()
326 password = module.params["password"]
327 expired = module.params["expired"]
328 ldap = module.params["ldap"]
329 roles = []
330 if module.params["roles"]:
331 roles = module.params["roles"].split(",")
332 roles = [_f for _f in roles if _f]
333 state = module.params["state"]
334 if state == "locked":
335 locked = True
336 else:
337 locked = False
338 db = ""
339 if module.params["db"]:
340 db = module.params["db"]
341
342 changed = False
343
344 try:
345 dsn = (
346 "Driver=Vertica;"
347 f"Server={module.params['cluster']};"
348 f"Port={module.params['port']};"
349 f"Database={db};"
350 f"User={module.params['login_user']};"
351 f"Password={module.params['login_password']};"
352 f"ConnectionLoadBalance=true"
353 )
354 db_conn = pyodbc.connect(dsn, autocommit=True)
355 cursor = db_conn.cursor()
356 except Exception as e:
357 module.fail_json(msg=f"Unable to connect to database: {e}.")
358
359 try:
360 user_facts = get_user_facts(cursor)
361 if module.check_mode:
362 changed = not check(user_facts, user, profile, resource_pool, locked, password, expired, ldap, roles)
363 elif state == "absent":
364 try:
365 changed = absent(user_facts, cursor, user, roles)
366 except pyodbc.Error as e:
367 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
368 elif state in ["present", "locked"]:
369 try:
370 changed = present(
371 user_facts, cursor, user, profile, resource_pool, locked, password, expired, ldap, roles
372 )
373 except pyodbc.Error as e:
374 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
375 except NotSupportedError as e:
376 module.fail_json(msg=f"{e}", ansible_facts={"vertica_users": user_facts})
377 except CannotDropError as e:
378 module.fail_json(msg=f"{e}", ansible_facts={"vertica_users": user_facts})
379 except SystemExit:
380 raise
381 except Exception as e:
382 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
383
384 module.exit_json(changed=changed, user=user, ansible_facts={"vertica_users": user_facts})
385
386
387 if __name__ == "__main__":
388 main()