| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2024, Aleksandr Vagachev (@aleksvagachev) <[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_user |
| 13 |
|
| 14 |
short_description: Creates or removes a ClickHouse user using the clickhouse-driver Client interface |
| 15 |
|
| 16 |
description: |
| 17 |
- Creates or removes a ClickHouse user using the |
| 18 |
L(clickhouse-driver,https://clickhouse-driver.readthedocs.io/en/latest) Client interface. |
| 19 |
- The module can only create and delete users, without any additional parameters. |
| 20 |
New features will be added in the future. |
| 21 |
|
| 22 |
attributes: |
| 23 |
check_mode: |
| 24 |
description: Supports check_mode. |
| 25 |
support: full |
| 26 |
|
| 27 |
author: |
| 28 |
- Aleksandr Vagachev (@aleksvagachev) |
| 29 |
- Andrew Klychkov (@Andersson007) |
| 30 |
|
| 31 |
extends_documentation_fragment: |
| 32 |
- community.clickhouse.client_inst_opts |
| 33 |
|
| 34 |
version_added: '0.4.0' |
| 35 |
|
| 36 |
options: |
| 37 |
state: |
| 38 |
description: |
| 39 |
- User state. |
| 40 |
- If C(present), will create the user if not exists. |
| 41 |
- If C(absent), will drop the user if exists. |
| 42 |
type: str |
| 43 |
choices: ['present', 'absent'] |
| 44 |
default: 'present' |
| 45 |
name: |
| 46 |
description: |
| 47 |
- User name to add or remove. |
| 48 |
type: str |
| 49 |
required: true |
| 50 |
password: |
| 51 |
description: |
| 52 |
- Set the user's password. |
| 53 |
- Password can be passed unhashed or hashed. |
| 54 |
- Cannot be used together with O(authentication). |
| 55 |
type: str |
| 56 |
type_password: |
| 57 |
description: |
| 58 |
- The type of password being transmitted(plaintext_password, sha256_password, sha256_hash...). |
| 59 |
- For more details, see U(https://clickhouse.com/docs/en/sql-reference/statements/create/user). |
| 60 |
- Cannot be used together with O(authentication). |
| 61 |
type: str |
| 62 |
default: sha256_password |
| 63 |
authentication: |
| 64 |
version_added: '2.1.0' |
| 65 |
description: |
| 66 |
- Set the user authentication. |
| 67 |
- Allows using LDAP, different hashing password. |
| 68 |
- Cannot be used together with legacy O(password) and O(type_password). |
| 69 |
type: dict |
| 70 |
suboptions: |
| 71 |
type: |
| 72 |
description: Authentication method to use. |
| 73 |
default: sha256_password |
| 74 |
type: str |
| 75 |
choices: |
| 76 |
- not_identified |
| 77 |
- no_password |
| 78 |
- plaintext_password |
| 79 |
- sha256_password |
| 80 |
- sha256_hash |
| 81 |
- double_sha1_password |
| 82 |
- double_sha1_hash |
| 83 |
- bcrypt_password |
| 84 |
- bcrypt_hash |
| 85 |
- ldap |
| 86 |
server: |
| 87 |
description: |
| 88 |
- Name of the server (required when I(type=ldap)). |
| 89 |
type: str |
| 90 |
password: |
| 91 |
description: |
| 92 |
- Password or hash. |
| 93 |
type: str |
| 94 |
cluster: |
| 95 |
description: |
| 96 |
- Run the command on all cluster hosts. |
| 97 |
- If the cluster is not configured, the command will crash with an error. |
| 98 |
type: str |
| 99 |
update_password: |
| 100 |
description: |
| 101 |
- If C(on_create), will set the password only for newly created users. |
| 102 |
If the user already exists, a C(password) value will be ignored. |
| 103 |
- If C(always), will always update the password. |
| 104 |
This option is not idempotent and will update the password even |
| 105 |
if it is the same in the database. If in future ClickHouse will allow |
| 106 |
to retrieve password hashes and other necessary details, this behavior |
| 107 |
will be changed. |
| 108 |
type: str |
| 109 |
choices: [always, on_create] |
| 110 |
default: on_create |
| 111 |
settings: |
| 112 |
description: |
| 113 |
- Settings with their constraints applied by default at user login. |
| 114 |
- You can also specify the profile from which the settings will be inherited. |
| 115 |
- When specified for an existing user, settings will only be updated if they differ from current settings. |
| 116 |
- The module fetches current settings from C(system.settings_profile_elements) for comparison. |
| 117 |
type: list |
| 118 |
elements: str |
| 119 |
version_added: '0.5.0' |
| 120 |
roles: |
| 121 |
description: |
| 122 |
- Grants specified roles to the user. |
| 123 |
- To append or remove roles, use the O(roles_mode) argument. |
| 124 |
- To revoke all roles, pass an empty list (C([])) and O(default_roles_mode=listed_only). |
| 125 |
type: list |
| 126 |
elements: str |
| 127 |
version_added: '0.6.0' |
| 128 |
default_roles: |
| 129 |
description: |
| 130 |
- Sets specified roles as default for the user. |
| 131 |
- The roles must be explicitly granted to the user whether manually |
| 132 |
before using this argument or by using the O(roles) |
| 133 |
argument in the same task. |
| 134 |
- To append or remove roles, use the O(default_roles_mode) argument. |
| 135 |
- To unset all roles as default, pass an empty list (C([])) and O(default_roles_mode=listed_only). |
| 136 |
type: list |
| 137 |
elements: str |
| 138 |
version_added: '0.6.0' |
| 139 |
roles_mode: |
| 140 |
description: |
| 141 |
- When C(listed_only) (default), makes the user a member of only roles specified in O(roles). |
| 142 |
It will remove the user from all other roles. |
| 143 |
- When C(append), appends roles specified in O(roles) to existing user roles. |
| 144 |
- When C(remove), removes roles specified in O(roles) from user roles. |
| 145 |
- The argument is ignored without O(roles) set. |
| 146 |
type: str |
| 147 |
choices: ['append', 'listed_only', 'remove'] |
| 148 |
default: 'listed_only' |
| 149 |
version_added: '0.6.0' |
| 150 |
default_roles_mode: |
| 151 |
description: |
| 152 |
- When C(listed_only) (default), sets only roles specified in O(default_roles) as user default roles. |
| 153 |
It will unset all other roles as default roles. |
| 154 |
- When C(append), appends roles specified in O(default_roles) to existing user default roles. |
| 155 |
default roles instead of unsetting not specified ones. |
| 156 |
- When C(remove), removes roles specified in O(default_roles) from user default roles. |
| 157 |
- Ignored without O(default_roles) set. |
| 158 |
type: str |
| 159 |
choices: ['append', 'listed_only', 'remove'] |
| 160 |
default: 'listed_only' |
| 161 |
version_added: '0.6.0' |
| 162 |
user_hosts: |
| 163 |
description: |
| 164 |
- Host restrictions to apply to the user. |
| 165 |
- It's a list of dictionaries, where each dictionary specifies the type of restriction to apply to which hosts or pattern. |
| 166 |
type: list |
| 167 |
elements: dict |
| 168 |
suboptions: |
| 169 |
type: |
| 170 |
description: |
| 171 |
- The method used to validate which hosts that users are allowed to connect from (V(ANY), V(LOCAL), V(IP), V(LIKE), V(NAME), V(REGEXP)). |
| 172 |
- When specified for an existing user the previous host type and hosts will be updated. |
| 173 |
- For more details, see U(https://clickhouse.com/docs/en/sql-reference/statements/create/user). |
| 174 |
type: str |
| 175 |
required: true |
| 176 |
hosts: |
| 177 |
description: |
| 178 |
- A list of hosts or patterns from which the user will be allowed to connect. |
| 179 |
- This is required if O(user_hosts.type) is not V(ANY) or V(LOCAL). |
| 180 |
type: list |
| 181 |
elements: str |
| 182 |
required: false |
| 183 |
version_added: '1.0.0' |
| 184 |
''' |
| 185 |
|
| 186 |
EXAMPLES = r''' |
| 187 |
- name: Create user granting roles and setting default role |
| 188 |
community.clickhouse.clickhouse_user: |
| 189 |
login_host: localhost |
| 190 |
login_user: alice |
| 191 |
login_db: foo |
| 192 |
login_password: my_password |
| 193 |
name: test_user |
| 194 |
authentication: |
| 195 |
password: qwerty |
| 196 |
type: sha256_password |
| 197 |
roles: |
| 198 |
- accountant |
| 199 |
- manager |
| 200 |
default_roles: |
| 201 |
- accountant |
| 202 |
|
| 203 |
- name: Append the sales role to test_user's roles |
| 204 |
community.clickhouse.clickhouse_user: |
| 205 |
login_host: localhost |
| 206 |
login_user: alice |
| 207 |
login_db: foo |
| 208 |
login_password: my_password |
| 209 |
name: test_user |
| 210 |
roles: |
| 211 |
- sales |
| 212 |
roles_mode: append |
| 213 |
|
| 214 |
- name: Unset all test_user's default roles |
| 215 |
community.clickhouse.clickhouse_user: |
| 216 |
login_host: localhost |
| 217 |
login_user: alice |
| 218 |
login_db: foo |
| 219 |
login_password: my_password |
| 220 |
name: test_user |
| 221 |
default_roles: [] |
| 222 |
|
| 223 |
- name: Revoke all roles from test_user |
| 224 |
community.clickhouse.clickhouse_user: |
| 225 |
login_host: localhost |
| 226 |
login_user: alice |
| 227 |
login_db: foo |
| 228 |
login_password: my_password |
| 229 |
name: test_user |
| 230 |
roles: [] |
| 231 |
|
| 232 |
- name: If user exists, update password |
| 233 |
community.clickhouse.clickhouse_user: |
| 234 |
login_host: localhost |
| 235 |
login_user: alice |
| 236 |
login_db: foo |
| 237 |
login_password: my_password |
| 238 |
name: test_user |
| 239 |
authentication: |
| 240 |
password: qwerty123 |
| 241 |
update_password: always |
| 242 |
|
| 243 |
- name: Update user settings (idempotent - only updates if different) |
| 244 |
community.clickhouse.clickhouse_user: |
| 245 |
login_host: localhost |
| 246 |
login_user: alice |
| 247 |
login_db: foo |
| 248 |
login_password: my_password |
| 249 |
name: test_user |
| 250 |
settings: |
| 251 |
- max_memory_usage = 20000 READONLY |
| 252 |
- max_threads = 8 |
| 253 |
|
| 254 |
- name: Create user with specific settings |
| 255 |
community.clickhouse.clickhouse_user: |
| 256 |
login_host: localhost |
| 257 |
login_user: alice |
| 258 |
login_db: foo |
| 259 |
login_password: my_password |
| 260 |
name: test_user |
| 261 |
authentication: |
| 262 |
password: 9e69e7e29351ad837503c44a5971edebc9b7e6d8601c89c284b1b59bf37afa80 |
| 263 |
type: sha256_hash |
| 264 |
cluster: test_cluster |
| 265 |
settings: |
| 266 |
- max_memory_usage = 15000 MIN 15000 MAX 16000 READONLY |
| 267 |
- PROFILE 'restricted' |
| 268 |
state: present |
| 269 |
|
| 270 |
- name: Create a user that can only connect from a specified host |
| 271 |
community.clickhouse.clickhouse_user: |
| 272 |
login_host: localhost |
| 273 |
login_user: alice |
| 274 |
login_db: foo |
| 275 |
login_password: my_password |
| 276 |
name: test_user |
| 277 |
user_hosts: |
| 278 |
- type: NAME |
| 279 |
hosts: |
| 280 |
- 'host1' |
| 281 |
|
| 282 |
- name: Update user host restrictions. Any previous host restrictions will be replaced. (idempotent - only updates if different) |
| 283 |
community.clickhouse.clickhouse_user: |
| 284 |
login_host: localhost |
| 285 |
login_user: alice |
| 286 |
login_db: foo |
| 287 |
login_password: my_password |
| 288 |
name: test_user |
| 289 |
user_hosts: |
| 290 |
- type: LIKE |
| 291 |
hosts: |
| 292 |
- '%.example.com' |
| 293 |
|
| 294 |
- name: Drop user |
| 295 |
community.clickhouse.clickhouse_user: |
| 296 |
login_host: localhost |
| 297 |
login_user: alice |
| 298 |
login_db: foo |
| 299 |
login_password: my_password |
| 300 |
name: test_user |
| 301 |
state: absent |
| 302 |
|
| 303 |
- name: Create user identified with ldap |
| 304 |
community.clickhouse.clickhouse_user: |
| 305 |
name: alice |
| 306 |
state: present |
| 307 |
authentication: |
| 308 |
type: ldap |
| 309 |
server: ad |
| 310 |
|
| 311 |
- name: Create user identified with password |
| 312 |
community.clickhouse.clickhouse_user: |
| 313 |
name: alice |
| 314 |
state: present |
| 315 |
authentication: |
| 316 |
password: my_password |
| 317 |
|
| 318 |
- name: Create user identified with passed hash |
| 319 |
community.clickhouse.clickhouse_user: |
| 320 |
name: alice |
| 321 |
state: present |
| 322 |
authentication: |
| 323 |
type: sha256_hash |
| 324 |
password: my_hash |
| 325 |
''' |
| 326 |
|
| 327 |
RETURN = r''' |
| 328 |
executed_statements: |
| 329 |
description: |
| 330 |
- Data-modifying executed statements. |
| 331 |
returned: on success |
| 332 |
type: list |
| 333 |
sample: ["CREATE USER test_user IDENTIFIED WITH ***** BY '*****'"] |
| 334 |
''' |
| 335 |
|
| 336 |
from ansible.module_utils.basic import AnsibleModule |
| 337 |
|
| 338 |
from ansible_collections.community.clickhouse.plugins.module_utils.clickhouse import ( |
| 339 |
check_clickhouse_driver, |
| 340 |
client_common_argument_spec, |
| 341 |
connect_to_db_via_client, |
| 342 |
execute_query, |
| 343 |
get_main_conn_kwargs, |
| 344 |
) |
| 345 |
|
| 346 |
PRIV_ERR_CODE = 497 |
| 347 |
executed_statements = [] |
| 348 |
|
| 349 |
|
| 350 |
class ClickHouseUser(): |
| 351 |
def __init__(self, module, client, name): |
| 352 |
self.changed = False |
| 353 |
self.module = module |
| 354 |
self.client = client |
| 355 |
self.name = name |
| 356 |
# Set default values, then update |
| 357 |
self.user_exists = False |
| 358 |
self.current_default_roles = [] |
| 359 |
self.current_roles = [] |
| 360 |
self.current_settings = {} |
| 361 |
self.current_user_hosts = {} |
| 362 |
# Fetch actual values from DB and |
| 363 |
# update the attributes with them |
| 364 |
self.__populate_info() |
| 365 |
|
| 366 |
def __populate_info(self): |
| 367 |
# Collecting user information |
| 368 |
query = ("SELECT name, storage, auth_type, default_roles_list " |
| 369 |
"FROM system.users " |
| 370 |
"WHERE name = '%s'" % self.name) |
| 371 |
|
| 372 |
result = execute_query(self.module, self.client, query) |
| 373 |
|
| 374 |
if result == PRIV_ERR_CODE: |
| 375 |
login_user = self.module.params['login_user'] |
| 376 |
msg = "Not enough privileges for user: %s" % login_user |
| 377 |
self.module.fail_json(msg=msg) |
| 378 |
|
| 379 |
if result != []: |
| 380 |
self.user_exists = True |
| 381 |
self.current_default_roles = result[0][3] |
| 382 |
|
| 383 |
if self.user_exists: |
| 384 |
self.current_roles = self.__fetch_user_groups() |
| 385 |
self.current_settings = self.__fetch_user_settings() |
| 386 |
self.current_user_hosts = self.__fetch_user_hosts() |
| 387 |
|
| 388 |
def __fetch_user_groups(self): |
| 389 |
query = ("SELECT granted_role_name FROM system.role_grants " |
| 390 |
"WHERE user_name = '%s'" % self.name) |
| 391 |
result = execute_query(self.module, self.client, query) |
| 392 |
return [row[0] for row in result] |
| 393 |
|
| 394 |
def __fetch_user_settings(self): |
| 395 |
"""Fetch current user settings from system.settings_profile_elements""" |
| 396 |
query = ("SELECT setting_name, value, min, max, writability, inherit_profile " |
| 397 |
"FROM system.settings_profile_elements " |
| 398 |
"WHERE user_name = '%s'" % self.name) |
| 399 |
result = execute_query(self.module, self.client, query) |
| 400 |
|
| 401 |
# Build a dict of current settings with their full definition |
| 402 |
settings_dict = {} |
| 403 |
for row in result: |
| 404 |
setting_name, value, min_val, max_val, writability, inherit_profile = row |
| 405 |
|
| 406 |
# Handle PROFILE inheritance separately |
| 407 |
if inherit_profile is not None: |
| 408 |
settings_dict[inherit_profile] = "PROFILE %s" % inherit_profile |
| 409 |
continue |
| 410 |
|
| 411 |
# Skip if it's not a regular setting (setting_name could be None for profiles) |
| 412 |
if setting_name is None: |
| 413 |
continue |
| 414 |
|
| 415 |
# Build the setting string as it would appear in ALTER USER |
| 416 |
setting_parts = [setting_name] |
| 417 |
if value is not None: |
| 418 |
setting_parts.extend(["=", str(value)]) |
| 419 |
if min_val is not None: |
| 420 |
setting_parts.extend(["MIN", str(min_val)]) |
| 421 |
if max_val is not None: |
| 422 |
setting_parts.extend(["MAX", str(max_val)]) |
| 423 |
if writability is not None and writability != 'WRITABLE': |
| 424 |
# Map writability enum to SQL keywords |
| 425 |
if writability == 'CONST': |
| 426 |
setting_parts.append("READONLY") |
| 427 |
elif writability == 'CHANGEABLE_IN_READONLY': |
| 428 |
setting_parts.append("CHANGEABLE_IN_READONLY") |
| 429 |
|
| 430 |
settings_dict[setting_name] = " ".join(setting_parts) |
| 431 |
|
| 432 |
return settings_dict |
| 433 |
|
| 434 |
def __fetch_user_hosts(self): |
| 435 |
"""Fetch current user host restrictions from system.users""" |
| 436 |
query = ("SELECT host_ip, host_names, host_names_regexp, host_names_like FROM system.users " |
| 437 |
"WHERE name = '%s'" % self.name) |
| 438 |
result = execute_query(self.module, self.client, query) |
| 439 |
|
| 440 |
user_hosts_dict = { |
| 441 |
'IP': set(result[0][0]), # HOST ANY is represented by ['::/0'] in host_ip |
| 442 |
'NAME': set(result[0][1]), # HOST LOCAL is represented by ['localhost'] in host_names |
| 443 |
'REGEXP': set(result[0][2]), |
| 444 |
'LIKE': set(result[0][3]), |
| 445 |
} |
| 446 |
|
| 447 |
return user_hosts_dict |
| 448 |
|
| 449 |
def create(self, type_password, password, cluster, user_hosts, settings, |
| 450 |
roles, roles_mode, default_roles, default_roles_mode, authentication): |
| 451 |
|
| 452 |
query = "CREATE USER '%s'" % self.name |
| 453 |
|
| 454 |
ident_clause = self._build_identified_clause( |
| 455 |
auth=authentication, |
| 456 |
legacy_type_password=type_password, |
| 457 |
legacy_password=password, |
| 458 |
) |
| 459 |
query += "%s" % ident_clause |
| 460 |
|
| 461 |
if user_hosts: |
| 462 |
query += " %s" % self.__build_user_host_clause(user_hosts) |
| 463 |
|
| 464 |
if cluster: |
| 465 |
query += " ON CLUSTER %s" % cluster |
| 466 |
|
| 467 |
if settings: |
| 468 |
query += " SETTINGS" |
| 469 |
for index, value in enumerate(settings): |
| 470 |
query += " %s" % value |
| 471 |
if index < len(settings) - 1: |
| 472 |
query += "," |
| 473 |
|
| 474 |
executed_statements.append(query) |
| 475 |
|
| 476 |
if not self.module.check_mode: |
| 477 |
execute_query(self.module, self.client, query) |
| 478 |
|
| 479 |
if roles and roles_mode != 'remove': |
| 480 |
self.__grant_roles(roles, cluster) |
| 481 |
|
| 482 |
if default_roles and default_roles_mode != 'remove': |
| 483 |
self.__set_default_roles(default_roles, cluster) |
| 484 |
|
| 485 |
return True |
| 486 |
|
| 487 |
def update(self, update_password, type_password, password, cluster, user_hosts, |
| 488 |
roles, roles_mode, default_roles, default_roles_mode, settings, authentication): |
| 489 |
|
| 490 |
if roles is not None: |
| 491 |
self.__update_roles(roles, roles_mode, cluster) |
| 492 |
|
| 493 |
if default_roles is not None: |
| 494 |
self.__update_default_roles(default_roles, default_roles_mode, cluster) |
| 495 |
|
| 496 |
self.__update_passwd(update_password, type_password, password, cluster, authentication) |
| 497 |
|
| 498 |
if user_hosts is not None: |
| 499 |
self.__update_host(user_hosts, cluster) |
| 500 |
|
| 501 |
if settings is not None: |
| 502 |
self.__update_settings(settings, cluster) |
| 503 |
|
| 504 |
return self.changed |
| 505 |
|
| 506 |
def drop(self, cluster): |
| 507 |
query = "DROP USER '%s'" % self.name |
| 508 |
if cluster: |
| 509 |
query += " ON CLUSTER %s" % cluster |
| 510 |
|
| 511 |
executed_statements.append(query) |
| 512 |
|
| 513 |
if not self.module.check_mode: |
| 514 |
execute_query(self.module, self.client, query) |
| 515 |
|
| 516 |
return True |
| 517 |
|
| 518 |
def __update_roles(self, desired_roles, mode, cluster): |
| 519 |
des = set(desired_roles) |
| 520 |
cur = set(self.current_roles) |
| 521 |
|
| 522 |
if mode == 'remove': |
| 523 |
# Remove only roles already present in current roles |
| 524 |
roles_to_revoke = list(des & cur) |
| 525 |
if roles_to_revoke: |
| 526 |
self.__revoke_roles(roles_to_revoke, cluster) |
| 527 |
|
| 528 |
elif mode == 'append': |
| 529 |
# Grant only roles from decired that |
| 530 |
# are not already present in current roles |
| 531 |
roles_to_grant = list(des - cur) |
| 532 |
if roles_to_grant: |
| 533 |
self.__grant_roles(roles_to_grant, cluster) |
| 534 |
|
| 535 |
elif mode == 'listed_only': |
| 536 |
if desired_roles == [] and self.current_roles: |
| 537 |
self.__revoke_roles(self.current_roles, cluster) |
| 538 |
elif desired_roles != []: |
| 539 |
roles_to_grant = list(des - cur) |
| 540 |
roles_to_revoke = list(cur - des) |
| 541 |
if roles_to_grant: |
| 542 |
self.__grant_roles(roles_to_grant, cluster) |
| 543 |
if roles_to_revoke: |
| 544 |
self.__revoke_roles(roles_to_revoke, cluster) |
| 545 |
|
| 546 |
def __update_default_roles(self, desired_def_roles, mode, cluster): |
| 547 |
des = set(desired_def_roles) |
| 548 |
cur = set(self.current_default_roles) |
| 549 |
|
| 550 |
if mode == 'remove' and des & cur: |
| 551 |
if desired_def_roles != []: |
| 552 |
# In this case, "desired" means "desired to get removed" |
| 553 |
self.__set_default_roles(list(cur - des), cluster) |
| 554 |
|
| 555 |
elif mode == 'append': |
| 556 |
if desired_def_roles != [] and des != cur: |
| 557 |
self.__set_default_roles(list(cur.union(des)), cluster) |
| 558 |
|
| 559 |
elif mode == 'listed_only': |
| 560 |
if desired_def_roles == [] and self.current_roles: |
| 561 |
self.__unset_default_roles() |
| 562 |
|
| 563 |
elif desired_def_roles != [] and des != cur: |
| 564 |
self.__set_default_roles(desired_def_roles, cluster) |
| 565 |
|
| 566 |
def __update_passwd(self, update_password, type_pwd, pwd, cluster, authentication): |
| 567 |
if update_password == 'on_create': |
| 568 |
return False or self.changed |
| 569 |
|
| 570 |
# If update_password is always |
| 571 |
# TODO: When ClickHouse will allow to retrieve password hashes, |
| 572 |
# make this idempotent, i.e. execute this only if the passwords don't match |
| 573 |
|
| 574 |
query = "ALTER USER '%s'" % self.name |
| 575 |
|
| 576 |
if cluster: |
| 577 |
query += " ON CLUSTER %s" % cluster |
| 578 |
|
| 579 |
ident_clause = self._build_identified_clause( |
| 580 |
auth=authentication, |
| 581 |
legacy_type_password=type_pwd, |
| 582 |
legacy_password=pwd, |
| 583 |
) |
| 584 |
|
| 585 |
query += "%s" % ident_clause |
| 586 |
|
| 587 |
executed_statements.append(query) |
| 588 |
|
| 589 |
if not self.module.check_mode: |
| 590 |
execute_query(self.module, self.client, query) |
| 591 |
|
| 592 |
self.changed = True |
| 593 |
|
| 594 |
def __update_host(self, user_hosts, cluster): |
| 595 |
des = self.__get_desired_user_hosts(user_hosts) |
| 596 |
cur = self.current_user_hosts |
| 597 |
|
| 598 |
if des == cur: |
| 599 |
return |
| 600 |
|
| 601 |
query = "ALTER USER '%s' %s" % (self.name, self.__build_user_host_clause(user_hosts)) |
| 602 |
|
| 603 |
if cluster: |
| 604 |
query += " ON CLUSTER %s" % cluster |
| 605 |
|
| 606 |
executed_statements.append(query) |
| 607 |
|
| 608 |
if not self.module.check_mode: |
| 609 |
execute_query(self.module, self.client, query) |
| 610 |
|
| 611 |
self.changed = True |
| 612 |
|
| 613 |
def __get_desired_user_hosts(self, user_hosts): |
| 614 |
desired_hosts = { |
| 615 |
'IP': set(), |
| 616 |
'NAME': set(), |
| 617 |
'REGEXP': set(), |
| 618 |
'LIKE': set(), |
| 619 |
} |
| 620 |
for host_restriction in user_hosts: |
| 621 |
host_type = host_restriction['type'].upper() |
| 622 |
if host_type == 'ANY': |
| 623 |
# ANY overrides all other restrictions |
| 624 |
return { |
| 625 |
'IP': set(['::/0']), |
| 626 |
'NAME': set(), |
| 627 |
'REGEXP': set(), |
| 628 |
'LIKE': set(), |
| 629 |
} |
| 630 |
elif host_type.upper() == 'LOCAL': |
| 631 |
desired_hosts['NAME'].add('localhost') |
| 632 |
else: |
| 633 |
hosts = host_restriction.get('hosts', []) |
| 634 |
desired_hosts[host_type].update(hosts) |
| 635 |
|
| 636 |
return desired_hosts |
| 637 |
|
| 638 |
def __build_user_host_clause(self, user_hosts): |
| 639 |
# If ANY is specified among host restrictions, it overrides all others |
| 640 |
if 'ANY' in [hr['type'].upper() for hr in user_hosts]: |
| 641 |
return "HOST ANY" |
| 642 |
|
| 643 |
clauses = [] |
| 644 |
for host_restriction in user_hosts: |
| 645 |
host_type = host_restriction['type'] |
| 646 |
|
| 647 |
if host_type.upper() == 'LOCAL': |
| 648 |
clauses.append("HOST %s" % host_type) |
| 649 |
else: |
| 650 |
hosts = host_restriction.get('hosts') |
| 651 |
clauses.append("HOST %s %s" % (host_type, ', '.join("'{0}'".format(h) for h in hosts))) |
| 652 |
|
| 653 |
return ' '.join(clauses) |
| 654 |
|
| 655 |
def __grant_roles(self, roles_to_set, cluster): |
| 656 |
query = "GRANT %s TO '%s'" % (', '.join(roles_to_set), self.name) |
| 657 |
executed_statements.append(query) |
| 658 |
|
| 659 |
if cluster: |
| 660 |
query += " ON CLUSTER %s" % cluster |
| 661 |
|
| 662 |
if not self.module.check_mode: |
| 663 |
execute_query(self.module, self.client, query) |
| 664 |
|
| 665 |
self.changed = True |
| 666 |
|
| 667 |
def __revoke_roles(self, roles_to_revoke, cluster): |
| 668 |
query = "REVOKE %s FROM '%s'" % (', '.join(roles_to_revoke), self.name) |
| 669 |
executed_statements.append(query) |
| 670 |
|
| 671 |
if cluster: |
| 672 |
query += " ON CLUSTER %s" % cluster |
| 673 |
|
| 674 |
if not self.module.check_mode: |
| 675 |
execute_query(self.module, self.client, query) |
| 676 |
|
| 677 |
self.changed = True |
| 678 |
|
| 679 |
def __set_default_roles(self, roles_to_set, cluster): |
| 680 |
self.current_roles = self.__fetch_user_groups() |
| 681 |
for role in roles_to_set: |
| 682 |
if role not in self.current_roles and role not in self.module.params["roles"]: |
| 683 |
self.module.fail_json("User %s is not in %s role. Grant it explicitly first." % (self.name, role)) |
| 684 |
|
| 685 |
query = "ALTER USER '%s' DEFAULT ROLE %s" % (self.name, ', '.join(roles_to_set)) |
| 686 |
if cluster: |
| 687 |
query += " ON CLUSTER %s" % cluster |
| 688 |
executed_statements.append(query) |
| 689 |
|
| 690 |
if not self.module.check_mode: |
| 691 |
execute_query(self.module, self.client, query) |
| 692 |
|
| 693 |
self.changed = True |
| 694 |
|
| 695 |
def __unset_default_roles(self): |
| 696 |
query = "SET DEFAULT ROLE NONE TO '%s'" % self.name |
| 697 |
executed_statements.append(query) |
| 698 |
|
| 699 |
if not self.module.check_mode: |
| 700 |
execute_query(self.module, self.client, query) |
| 701 |
|
| 702 |
self.changed = True |
| 703 |
|
| 704 |
def __update_settings(self, settings, cluster): |
| 705 |
"""Update user settings idempotently by comparing with current settings""" |
| 706 |
# Parse desired settings into a comparable format |
| 707 |
desired_settings = {} |
| 708 |
desired_profiles = [] |
| 709 |
|
| 710 |
for setting in settings: |
| 711 |
setting_upper = setting.upper() |
| 712 |
# Handle PROFILE separately as it's not a regular setting |
| 713 |
if 'PROFILE' in setting_upper: |
| 714 |
# Extract profile name (handle both PROFILE 'name' and PROFILE name) |
| 715 |
profile_part = setting.split(None, 1)[1].strip().strip("'\"") |
| 716 |
desired_profiles.append(profile_part) |
| 717 |
else: |
| 718 |
# Extract setting name (first word before = or space) |
| 719 |
setting_name = setting.split()[0].split('=')[0].strip() |
| 720 |
# Normalize the setting string for comparison |
| 721 |
normalized = ' '.join(setting.split()) |
| 722 |
desired_settings[setting_name] = normalized |
| 723 |
|
| 724 |
# Compare current with desired |
| 725 |
needs_update = False |
| 726 |
|
| 727 |
# Check if any setting values differ |
| 728 |
for setting_name, desired_def in desired_settings.items(): |
| 729 |
current_def = self.current_settings.get(setting_name, '') |
| 730 |
# Normalize both for comparison (case-insensitive, whitespace-normalized) |
| 731 |
current_normalized = ' '.join(current_def.upper().split()) |
| 732 |
desired_normalized = ' '.join(desired_def.upper().split()) |
| 733 |
|
| 734 |
if current_normalized != desired_normalized: |
| 735 |
needs_update = True |
| 736 |
break |
| 737 |
|
| 738 |
# Check if there are settings to remove (current has settings not in desired) |
| 739 |
if not needs_update: |
| 740 |
for setting_name in self.current_settings: |
| 741 |
if setting_name not in desired_settings: |
| 742 |
# There's a setting currently applied that's not in desired |
| 743 |
# We need to reapply to remove it |
| 744 |
needs_update = True |
| 745 |
break |
| 746 |
|
| 747 |
# Only update if settings actually differ |
| 748 |
if not needs_update: |
| 749 |
return |
| 750 |
|
| 751 |
# Build the ALTER USER query |
| 752 |
query = "ALTER USER '%s' SETTINGS" % self.name |
| 753 |
for index, value in enumerate(settings): |
| 754 |
query += " %s" % value |
| 755 |
if index < len(settings) - 1: |
| 756 |
query += "," |
| 757 |
|
| 758 |
if cluster: |
| 759 |
query += " ON CLUSTER %s" % cluster |
| 760 |
|
| 761 |
executed_statements.append(query) |
| 762 |
|
| 763 |
if not self.module.check_mode: |
| 764 |
execute_query(self.module, self.client, query) |
| 765 |
|
| 766 |
self.changed = True |
| 767 |
|
| 768 |
def _build_identified_clause(self, auth=None, legacy_type_password=None, legacy_password=None): |
| 769 |
if auth and isinstance(auth, dict): |
| 770 |
atype = auth.get('type', '').lower().strip() |
| 771 |
|
| 772 |
if atype == "not_identified": |
| 773 |
return " NOT IDENTIFIED" |
| 774 |
|
| 775 |
if atype == 'no_password': |
| 776 |
return " IDENTIFIED WITH NO_PASSWORD" |
| 777 |
|
| 778 |
if atype == 'ldap': |
| 779 |
server = auth.get('server') |
| 780 |
if not server: |
| 781 |
self.module.fail_json(msg="authentication.type=ldap requires 'server'") |
| 782 |
return f" IDENTIFIED WITH ldap SERVER '{server}'" |
| 783 |
|
| 784 |
password = auth.get('password') or legacy_password |
| 785 |
if password is None: |
| 786 |
self.module.fail_json(msg=f"type {atype} requires password") |
| 787 |
|
| 788 |
if atype in ('plaintext_password', 'sha256_password', 'double_sha1_password', 'bcrypt_password'): |
| 789 |
return f" IDENTIFIED WITH {atype} BY '{password}'" |
| 790 |
|
| 791 |
# Separate so maybe in future add salt here. |
| 792 |
if atype in ('sha256_hash', 'double_sha1_hash', 'bcrypt_hash'): |
| 793 |
return f" IDENTIFIED WITH {atype} BY '{password}'" |
| 794 |
|
| 795 |
self.module.fail_json(msg=f"type {atype} not implemented") |
| 796 |
|
| 797 |
# Backward compatibility |
| 798 |
if legacy_password is not None: |
| 799 |
return f" IDENTIFIED WITH {legacy_type_password} BY '{legacy_password}'" |
| 800 |
return "" |
| 801 |
|
| 802 |
|
| 803 |
def main(): |
| 804 |
argument_spec = client_common_argument_spec() |
| 805 |
argument_spec.update( |
| 806 |
state=dict(type='str', choices=['present', 'absent'], default='present'), |
| 807 |
name=dict(type='str', required=True), |
| 808 |
password=dict(type='str', default=None, no_log=True), |
| 809 |
type_password=dict(type='str', default='sha256_password', no_log=False), |
| 810 |
authentication=dict( |
| 811 |
type='dict', |
| 812 |
default=None, |
| 813 |
options=dict( |
| 814 |
type=dict( |
| 815 |
type='str', |
| 816 |
default='sha256_password', |
| 817 |
choices=[ |
| 818 |
'not_identified', |
| 819 |
'no_password', |
| 820 |
'plaintext_password', |
| 821 |
'sha256_password', |
| 822 |
'sha256_hash', |
| 823 |
'double_sha1_password', |
| 824 |
'double_sha1_hash', |
| 825 |
'bcrypt_password', |
| 826 |
'bcrypt_hash', |
| 827 |
'ldap' |
| 828 |
] |
| 829 |
), |
| 830 |
server=dict(type='str'), |
| 831 |
password=dict(type='str', no_log=True), |
| 832 |
), |
| 833 |
), |
| 834 |
cluster=dict(type='str', default=None), |
| 835 |
update_password=dict( |
| 836 |
type='str', choices=['always', 'on_create'], |
| 837 |
default='on_create', no_log=False |
| 838 |
), |
| 839 |
user_hosts=dict(type='list', elements='dict'), |
| 840 |
settings=dict(type='list', elements='str'), |
| 841 |
roles=dict(type='list', elements='str', default=None), |
| 842 |
default_roles=dict(type='list', elements='str', default=None), |
| 843 |
roles_mode=dict(type='str', choices=['listed_only', 'append', 'remove'], |
| 844 |
default='listed_only'), |
| 845 |
default_roles_mode=dict(type='str', choices=['listed_only', 'append', 'remove'], |
| 846 |
default='listed_only'), |
| 847 |
) |
| 848 |
|
| 849 |
# Instantiate an object of module class |
| 850 |
module = AnsibleModule( |
| 851 |
argument_spec=argument_spec, |
| 852 |
supports_check_mode=True, |
| 853 |
mutually_exclusive=[['password', 'authentication']], |
| 854 |
) |
| 855 |
|
| 856 |
# Assign passed options to variables |
| 857 |
client_kwargs = module.params['client_kwargs'] |
| 858 |
# The reason why these arguments are separate from client_kwargs |
| 859 |
# is that we need to protect some sensitive data like passwords passed |
| 860 |
# to the module from logging (see the arguments above with no_log=True); |
| 861 |
# Such data must be passed as module arguments (not nested deep in values). |
| 862 |
main_conn_kwargs = get_main_conn_kwargs(module) |
| 863 |
state = module.params['state'] |
| 864 |
name = module.params['name'] |
| 865 |
password = module.params["password"] |
| 866 |
type_password = module.params["type_password"] |
| 867 |
cluster = module.params['cluster'] |
| 868 |
update_password = module.params['update_password'] |
| 869 |
user_hosts = module.params['user_hosts'] |
| 870 |
settings = module.params['settings'] |
| 871 |
roles = module.params['roles'] |
| 872 |
roles_mode = module.params['roles_mode'] |
| 873 |
default_roles = module.params['default_roles'] |
| 874 |
default_roles_mode = module.params['default_roles_mode'] |
| 875 |
authentication = module.params['authentication'] |
| 876 |
|
| 877 |
# Will fail if no driver informing the user |
| 878 |
check_clickhouse_driver(module) |
| 879 |
|
| 880 |
# Connect to DB |
| 881 |
client = connect_to_db_via_client(module, main_conn_kwargs, client_kwargs) |
| 882 |
|
| 883 |
# Do the job |
| 884 |
changed = False |
| 885 |
user = ClickHouseUser(module, client, name) |
| 886 |
|
| 887 |
if state == 'present': |
| 888 |
if not user.user_exists: |
| 889 |
changed = user.create(type_password, password, cluster, user_hosts, settings, |
| 890 |
roles, roles_mode, default_roles, default_roles_mode, authentication) |
| 891 |
else: |
| 892 |
# If user exists |
| 893 |
changed = user.update(update_password, type_password, password, cluster, user_hosts, |
| 894 |
roles, roles_mode, default_roles, default_roles_mode, settings, authentication) |
| 895 |
else: |
| 896 |
# If state is absent |
| 897 |
if user.user_exists: |
| 898 |
changed = user.drop(cluster) |
| 899 |
|
| 900 |
# Close connection |
| 901 |
client.disconnect_connection() |
| 902 |
|
| 903 |
# Users will get this in JSON output after execution |
| 904 |
module.exit_json(changed=changed, executed_statements=executed_statements) |
| 905 |
|
| 906 |
|
| 907 |
if __name__ == '__main__': |
| 908 |
main() |