Debian Codegraph @

ansible_collections/community/clickhouse/plugins/modules/clickhouse_grants.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2025, Andrew Klychkov (@Andersson007) <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import (absolute_import, division, print_function)
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: clickhouse_grants
13
14 short_description: Manage grants for ClickHouse users and roles
15
16 description:
17 - Grants, updates, or revokes privileges for ClickHouse users and roles.
18 - This module uses the L(clickhouse-driver,https://clickhouse-driver.readthedocs.io/en/latest) client interface.
19
20 attributes:
21 check_mode:
22 description: Supports check_mode.
23 support: full
24
25 author:
26 - Andrew Klychkov (@Andersson007)
27 - Fabian Kohn (@fako1024)
28
29 extends_documentation_fragment:
30 - community.clickhouse.client_inst_opts
31
32 version_added: '0.9.0'
33
34 options:
35 state:
36 description:
37 - If C(present), the module will grant or update privileges.
38 - If C(absent), the module will revoke all privileges from the O(grantee).
39 type: str
40 choices: ['present', 'absent']
41 default: 'present'
42 grantee:
43 description:
44 - A user or a role to grant, update, or revoke privileges for.
45 type: str
46 required: true
47 exclusive:
48 description:
49 - If set to C(false) (the default), the module will append
50 the privileges specified in O(privileges) to the privileges the O(grantee)
51 already has.
52 - If set to C(true), the module will revoke all
53 current privileges from the O(grantee) before granting the new ones.
54 type: bool
55 default: false
56 privileges:
57 description:
58 - Privileges to grant. This option is required when C(state) is C(present).
59 - It's a list of dictionaries, where each dictionary specifies a set of privileges on a database object.
60 type: list
61 elements: dict
62 suboptions:
63 object:
64 description:
65 - The database object to grant privileges on.
66 - Use C(*.*) for global privileges, C(database.*) for all tables in a database,
67 and C(database.table) for a specific table.
68 type: str
69 required: true
70 privs:
71 description:
72 - A dictionary of privileges.
73 - Keys are privilege names, like C(CREATE USER) or V(SELECT(column1, column2\)).
74 - Values are booleans indicating whether to grant the privilege
75 with the C(WITH GRANT OPTION).
76 - Alternatively, you can use the C(grant_option) parameter to apply the same setting to all privileges in this set.
77 type: dict
78 required: true
79 grant_option:
80 description:
81 - A boolean that applies to all privileges in this set.
82 - If specified, it overrides any individual grant option settings within C(privs).
83 type: bool
84 cluster:
85 description:
86 - Run the grant/revoke commands on all cluster hosts.
87 - If the cluster is not configured, the command will fail with an error.
88 type: str
89 version_added: '0.11.0'
90 '''
91
92 EXAMPLES = r'''
93 - name: Grant global privileges to a user
94 community.clickhouse.clickhouse_grants:
95 grantee: alice
96 privileges:
97 - object: '*.*'
98 privs:
99 "ALTER USER": true # With grant option
100 "CREATE DATABASE": false # Without grant option
101 "CREATE USER": false # Without grant option
102
103 - name: Grant privileges on a specific database
104 community.clickhouse.clickhouse_grants:
105 grantee: bob
106 privileges:
107 - object: 'infra.*'
108 privs:
109 "SELECT": true # With grant option
110 "INSERT": false # Without grant option
111
112 - name: Grant privileges on a cluster
113 community.clickhouse.clickhouse_grants:
114 grantee: bob
115 cluster: test_cluster
116 privileges:
117 - object: 'infra.*'
118 privs:
119 "SELECT": true # With grant option
120 "INSERT": false # Without grant option
121
122 - name: Grant SELECT on specific columns of a table
123 community.clickhouse.clickhouse_grants:
124 grantee: carol
125 privileges:
126 - object: 'sales.customers'
127 privs:
128 "SELECT(name, email)": false # Without grant option
129
130 - name: Replace all existing privileges for a user
131 community.clickhouse.clickhouse_grants:
132 grantee: david
133 exclusive: true
134 privileges:
135 - object: 'bar.*'
136 privs:
137 "SELECT": false # Without grant option
138
139 - name: Revoke all privileges from a user
140 community.clickhouse.clickhouse_grants:
141 grantee: eve
142 state: absent
143 '''
144
145 RETURN = r'''
146 executed_statements:
147 description:
148 - Data-modifying executed statements.
149 returned: on success
150 type: list
151 sample: ['GRANT SELECT ON foo.* TO alice', 'REVOKE INSERT ON foo.* FROM alice']
152 diff:
153 description:
154 - Differences between the previous and current state.
155 - Only returned when diff mode is enabled (with C(--diff) or in C(check_mode)).
156 returned: when diff mode is enabled or check_mode is true
157 type: dict
158 contains:
159 before:
160 description: Grants before the change.
161 returned: always
162 type: dict
163 sample:
164 "*.*":
165 "CREATE USER": false
166 "foo.*":
167 "INSERT": false
168 "SELECT": true
169 after:
170 description: Grants after the change.
171 returned: always
172 type: dict
173 sample:
174 "*.*":
175 "CREATE USER": false
176 "foo.*":
177 "DELETE": true
178 "INSERT": false
179 "SELECT": true
180 '''
181
182 import re
183 from collections import defaultdict
184
185 from ansible.module_utils.basic import AnsibleModule
186
187 from ansible_collections.community.clickhouse.plugins.module_utils.clickhouse import (
188 check_clickhouse_driver,
189 client_common_argument_spec,
190 connect_to_db_via_client,
191 execute_query,
192 get_main_conn_kwargs,
193 )
194
195 PRIV_ERR_CODE = 497
196 executed_statements = []
197
198 # Compile regex pattern once for performance
199 GRANT_REGEX = re.compile(r'GRANT (.+?) ON (.+?) TO .+?( WITH GRANT OPTION)?(?: ON CLUSTER .+)?$')
200
201
202 class ClickHouseGrants():
203 def __init__(self, module, client, grantee, cluster=None):
204 self.changed = False
205 self.module = module
206 self.client = client
207 self.grantee = grantee
208 self.cluster = cluster
209 self.__check_grantee_exists()
210
211 def __check_grantee_exists(self):
212 # Check if grantee exists as either a user or a role
213 query = ("SELECT 1 FROM system.users WHERE name = '%s' "
214 "UNION ALL "
215 "SELECT 1 FROM system.roles WHERE name = '%s' "
216 "LIMIT 1" % (self.grantee, self.grantee))
217
218 result = execute_query(self.module, self.client, query)
219
220 if result == PRIV_ERR_CODE:
221 login_user = self.module.params['login_user']
222 msg = "Not enough privileges for user: %s" % login_user
223 self.module.fail_json(msg=msg)
224
225 if not result:
226 self.module.fail_json(msg="Grantee %s does not exist" % self.grantee)
227
228 def get(self):
229 query = "SHOW GRANTS FOR '%s'" % self.grantee
230 result = execute_query(self.module, self.client, query)
231
232 if result == PRIV_ERR_CODE:
233 login_user = self.module.params['login_user']
234 msg = "Not enough privileges for user: %s to SHOW GRANTS" % login_user
235 self.module.fail_json(msg=msg)
236
237 grants = {}
238 for row in result:
239 grant_statement = row[0]
240 match = GRANT_REGEX.match(grant_statement)
241 if not match:
242 continue
243
244 privs_str, obj, grant_option_str = match.groups()
245 grant_option = (grant_option_str is not None)
246
247 # Normalize object name: ClickHouse 25.x returns '*' instead of '*.*' for global grants
248 if obj == '*':
249 obj = '*.*'
250
251 if obj not in grants:
252 grants[obj] = {}
253
254 privs = [p.strip().upper() for p in privs_str.split(',')]
255 for priv in privs:
256 grants[obj][priv] = grant_option
257
258 return grants
259
260 def _get_desired_grants(self):
261 privileges = self.module.params['privileges']
262 if not privileges:
263 return {}
264
265 desired_grants = {}
266 for p in privileges:
267 obj = p['object']
268 if obj not in desired_grants:
269 desired_grants[obj] = {}
270
271 grant_option_override = p.get('grant_option')
272 for priv, grant_option in p['privs'].items():
273 final_grant_option = grant_option_override if grant_option_override is not None else grant_option
274 desired_grants[obj][priv.upper()] = bool(final_grant_option)
275
276 return desired_grants
277
278 def update(self):
279 desired = self._get_desired_grants()
280 current = self.get()
281 exclusive = self.module.params['exclusive']
282
283 # Use set comprehensions for better performance
284 all_current_privs = {(priv, obj, go)
285 for obj, privs in current.items()
286 for priv, go in privs.items()}
287
288 all_desired_privs = {(priv, obj, go)
289 for obj, privs in desired.items()
290 for priv, go in privs.items()}
291
292 to_revoke = all_current_privs - all_desired_privs if exclusive else set()
293 to_grant = all_desired_privs - all_current_privs
294
295 if not to_revoke and not to_grant:
296 return self.changed
297
298 self.changed = True
299
300 queries = []
301 revokes_by_obj = defaultdict(list)
302 for priv, obj, go in to_revoke:
303 revokes_by_obj[obj].append(priv)
304
305 for obj, privs in revokes_by_obj.items():
306 privs_str = ', '.join(sorted(privs))
307 query = "REVOKE {0} ON {1} FROM '{2}'".format(privs_str, obj, self.grantee)
308 if self.cluster:
309 query += " ON CLUSTER {0}".format(self.cluster)
310 queries.append(query)
311
312 grants_go_by_obj = defaultdict(list)
313 grants_no_go_by_obj = defaultdict(list)
314
315 for priv, obj, go in to_grant:
316 if go:
317 grants_go_by_obj[obj].append(priv)
318 else:
319 grants_no_go_by_obj[obj].append(priv)
320
321 for obj, privs in grants_go_by_obj.items():
322 privs_str = ', '.join(sorted(privs))
323 query = "GRANT {0} ON {1} TO '{2}' WITH GRANT OPTION".format(privs_str, obj, self.grantee)
324 if self.cluster:
325 query += " ON CLUSTER {0}".format(self.cluster)
326 queries.append(query)
327
328 for obj, privs in grants_no_go_by_obj.items():
329 privs_str = ', '.join(sorted(privs))
330 query = "GRANT {0} ON {1} TO '{2}'".format(privs_str, obj, self.grantee)
331 if self.cluster:
332 query += " ON CLUSTER {0}".format(self.cluster)
333 queries.append(query)
334
335 executed_statements.extend(queries)
336
337 if self.module.check_mode:
338 return self.changed
339
340 for query in queries:
341 execute_query(self.module, self.client, query)
342
343 return self.changed
344
345 def revoke(self):
346 current = self.get()
347
348 if not current:
349 # No grants to revoke
350 return self.changed
351
352 self.changed = True
353
354 # Build revoke queries for all current privileges
355 queries = []
356 for obj, privs in current.items():
357 privs_str = ', '.join(sorted(privs))
358 query = "REVOKE {0} ON {1} FROM '{2}'".format(privs_str, obj, self.grantee)
359 if self.cluster:
360 query += " ON CLUSTER {0}".format(self.cluster)
361 queries.append(query)
362
363 executed_statements.extend(queries)
364
365 if self.module.check_mode:
366 return self.changed
367
368 for query in queries:
369 execute_query(self.module, self.client, query)
370
371 return self.changed
372
373
374 def main():
375 argument_spec = client_common_argument_spec()
376 argument_spec.update(
377 state=dict(type='str', choices=['present', 'absent'], default='present'),
378 grantee=dict(type='str', required=True),
379 exclusive=dict(type='bool', default=False),
380 privileges=dict(type='list', elements='dict'),
381 cluster=dict(type='str', default=None),
382 )
383
384 # Instantiate an object of module class
385 module = AnsibleModule(
386 argument_spec=argument_spec,
387 supports_check_mode=True,
388 required_if=[
389 ('state', 'present', ['privileges']),
390 ],
391 )
392
393 # Assign passed options to variables
394 client_kwargs = module.params['client_kwargs']
395 # The reason why these arguments are separate from client_kwargs
396 # is that we need to protect some sensitive data like passwords passed
397 # to the module from logging (see the arguments above with no_log=True);
398 # Such data must be passed as module arguments (not nested deep in values).
399 main_conn_kwargs = get_main_conn_kwargs(module)
400 state = module.params['state']
401 grantee = module.params['grantee']
402 cluster = module.params['cluster']
403
404 # Will fail if no driver informing the user
405 check_clickhouse_driver(module)
406
407 # Connect to DB
408 client = connect_to_db_via_client(module, main_conn_kwargs, client_kwargs)
409
410 # Do the job
411 changed = False
412 grants = ClickHouseGrants(module, client, grantee, cluster)
413 # Get current grants
414 start_grants = grants.get()
415
416 if state == 'present':
417 changed = grants.update()
418 elif state == 'absent':
419 changed = grants.revoke()
420
421 # Get end grants - in check_mode, compute expected state
422 if module.check_mode and changed:
423 # In check mode, compute what the end state would be
424 if state == 'absent':
425 end_grants = {}
426 else: # state == 'present'
427 desired_grants = grants._get_desired_grants()
428 if module.params['exclusive']:
429 end_grants = desired_grants
430 else:
431 # Merge current and desired grants (append mode)
432 end_grants = dict(start_grants)
433 for obj, privs in desired_grants.items():
434 if obj not in end_grants:
435 end_grants[obj] = {}
436 end_grants[obj].update(privs)
437 else:
438 # In normal mode or if no changes, query actual state
439 end_grants = grants.get()
440
441 # Close connection
442 client.disconnect_connection()
443
444 # Prepare result
445 result = {
446 'changed': changed,
447 'executed_statements': executed_statements,
448 }
449
450 # Add diff if in diff mode or check mode
451 if module._diff or module.check_mode:
452 result['diff'] = {
453 'before': start_grants,
454 'after': end_grants,
455 }
456
457 # Users will get this in JSON output after execution
458 module.exit_json(**result)
459
460
461 if __name__ == '__main__':
462 main()