| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2024, Don Naro (@oranod) <[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 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
--- |
| 13 |
module: clickhouse_role |
| 14 |
|
| 15 |
short_description: Creates or removes a ClickHouse role. |
| 16 |
|
| 17 |
description: |
| 18 |
- Creates or removes a ClickHouse role. |
| 19 |
|
| 20 |
attributes: |
| 21 |
check_mode: |
| 22 |
description: Supports check_mode. |
| 23 |
support: full |
| 24 |
|
| 25 |
version_added: '0.5.0' |
| 26 |
|
| 27 |
author: |
| 28 |
- Don Naro (@oranod) |
| 29 |
- Aleksandr Vagachev (@aleksvagachev) |
| 30 |
- Andrew Klychkov (@Andersson007) |
| 31 |
|
| 32 |
extends_documentation_fragment: |
| 33 |
- community.clickhouse.client_inst_opts |
| 34 |
|
| 35 |
options: |
| 36 |
state: |
| 37 |
description: |
| 38 |
- Role state. |
| 39 |
- C(present) creates the role if it does not exist. |
| 40 |
- C(absent) deletes the role if it exists. |
| 41 |
type: str |
| 42 |
choices: ['present', 'absent'] |
| 43 |
default: 'present' |
| 44 |
name: |
| 45 |
description: |
| 46 |
- Role name to add or remove. |
| 47 |
type: str |
| 48 |
required: true |
| 49 |
cluster: |
| 50 |
description: |
| 51 |
- Run the command on all cluster hosts. |
| 52 |
- If the cluster is not configured, the command will crash with an error. |
| 53 |
type: str |
| 54 |
settings: |
| 55 |
description: |
| 56 |
- Settings with their limitations that apply to the role. |
| 57 |
- You can also specify the profile from which the settings will be inherited. |
| 58 |
type: list |
| 59 |
elements: str |
| 60 |
""" |
| 61 |
|
| 62 |
EXAMPLES = r""" |
| 63 |
- name: Create role |
| 64 |
community.clickhouse.clickhouse_role: |
| 65 |
name: test_role |
| 66 |
state: present |
| 67 |
|
| 68 |
- name: Create a role with settings |
| 69 |
community.clickhouse.clickhouse_role: |
| 70 |
name: test_role |
| 71 |
state: present |
| 72 |
settings: |
| 73 |
- max_memory_usage = 15000 MIN 15000 MAX 16000 READONLY |
| 74 |
- PROFILE restricted |
| 75 |
cluster: test_cluster |
| 76 |
|
| 77 |
- name: Remove role |
| 78 |
community.clickhouse.clickhouse_role: |
| 79 |
name: test_role |
| 80 |
state: absent |
| 81 |
""" |
| 82 |
|
| 83 |
RETURN = r""" |
| 84 |
executed_statements: |
| 85 |
description: |
| 86 |
- Data-modifying executed statements. |
| 87 |
returned: on success |
| 88 |
type: list |
| 89 |
sample: ['CREATE ROLE test_role'] |
| 90 |
""" |
| 91 |
|
| 92 |
import re |
| 93 |
|
| 94 |
from ansible.module_utils.basic import AnsibleModule |
| 95 |
|
| 96 |
from ansible_collections.community.clickhouse.plugins.module_utils.clickhouse import ( |
| 97 |
check_clickhouse_driver, |
| 98 |
client_common_argument_spec, |
| 99 |
connect_to_db_via_client, |
| 100 |
execute_query, |
| 101 |
get_main_conn_kwargs, |
| 102 |
) |
| 103 |
|
| 104 |
executed_statements = [] |
| 105 |
|
| 106 |
|
| 107 |
class ClickHouseRole: |
| 108 |
def __init__(self, module, client, name): |
| 109 |
self.module = module |
| 110 |
self.client = client |
| 111 |
self.name = name |
| 112 |
self.exists = self.check_exists() |
| 113 |
|
| 114 |
def check_exists(self): |
| 115 |
query = "SELECT 1 FROM system.roles WHERE name = '%s' LIMIT 1" % self.name |
| 116 |
result = execute_query(self.module, self.client, query) |
| 117 |
return bool(result) |
| 118 |
|
| 119 |
def get_current_role_definition(self): |
| 120 |
"""Get current role definition using SHOW CREATE ROLE""" |
| 121 |
if not self.exists: |
| 122 |
return None |
| 123 |
|
| 124 |
query = "SHOW CREATE ROLE %s" % self.name |
| 125 |
result = execute_query(self.module, self.client, query) |
| 126 |
if result: |
| 127 |
return result[0][0] # SHOW CREATE ROLE returns single row with CREATE statement |
| 128 |
return None |
| 129 |
|
| 130 |
def parse_settings_from_create_statement(self, create_statement): |
| 131 |
"""Parse settings from CREATE ROLE statement""" |
| 132 |
if not create_statement or 'SETTINGS' not in create_statement: |
| 133 |
return [] |
| 134 |
|
| 135 |
# Extract settings part after SETTINGS keyword |
| 136 |
settings_part = create_statement.split('SETTINGS', 1)[1].strip() |
| 137 |
if not settings_part: |
| 138 |
return [] |
| 139 |
|
| 140 |
# Parse individual settings (this is a simplified parser) |
| 141 |
# In real implementation, we might need more sophisticated parsing |
| 142 |
settings = [] |
| 143 |
current_setting = "" |
| 144 |
paren_depth = 0 |
| 145 |
quote_char = None |
| 146 |
|
| 147 |
i = 0 |
| 148 |
while i < len(settings_part): |
| 149 |
char = settings_part[i] |
| 150 |
|
| 151 |
if quote_char: |
| 152 |
current_setting += char |
| 153 |
if char == quote_char and (i == 0 or settings_part[i - 1] != '\\'): |
| 154 |
quote_char = None |
| 155 |
elif char in ("'", '"'): |
| 156 |
current_setting += char |
| 157 |
quote_char = char |
| 158 |
elif char == '(': |
| 159 |
current_setting += char |
| 160 |
paren_depth += 1 |
| 161 |
elif char == ')': |
| 162 |
current_setting += char |
| 163 |
paren_depth -= 1 |
| 164 |
elif char == ',' and paren_depth == 0: |
| 165 |
settings.append(current_setting.strip()) |
| 166 |
current_setting = "" |
| 167 |
else: |
| 168 |
current_setting += char |
| 169 |
i += 1 |
| 170 |
|
| 171 |
if current_setting.strip(): |
| 172 |
settings.append(current_setting.strip()) |
| 173 |
|
| 174 |
return settings |
| 175 |
|
| 176 |
def normalize_settings(self, settings_list): |
| 177 |
"""Normalize settings for comparison""" |
| 178 |
if not settings_list: |
| 179 |
return [] |
| 180 |
|
| 181 |
normalized = [] |
| 182 |
for setting in settings_list: |
| 183 |
# Remove extra whitespace and standardize format |
| 184 |
normalized_setting = ' '.join(setting.split()) |
| 185 |
|
| 186 |
# ClickHouse normalizes some constraint types |
| 187 |
# Different versions may use CONST or READONLY interchangeably |
| 188 |
# Since READONLY is an alias for CONST in ClickHouse, normalize both to CONST |
| 189 |
normalized_setting = re.sub(r'\bREADONLY\b', 'CONST', normalized_setting) |
| 190 |
|
| 191 |
# ClickHouse may handle profile names differently across versions |
| 192 |
# Normalize quoted and unquoted profile names |
| 193 |
# PROFILE 'default' -> PROFILE default, PROFILE "default" -> PROFILE default |
| 194 |
normalized_setting = re.sub(r"PROFILE\s+'([^']+)'", r"PROFILE \1", normalized_setting) |
| 195 |
normalized_setting = re.sub(r'PROFILE\s+"([^"]+)"', r"PROFILE \1", normalized_setting) |
| 196 |
|
| 197 |
# Also handle case where profile name might be output with backticks |
| 198 |
normalized_setting = re.sub(r"PROFILE\s+`([^`]+)`", r"PROFILE \1", normalized_setting) |
| 199 |
|
| 200 |
normalized.append(normalized_setting) |
| 201 |
|
| 202 |
return sorted(normalized) |
| 203 |
|
| 204 |
def settings_changed(self, current_settings, desired_settings): |
| 205 |
"""Check if settings have changed""" |
| 206 |
current_normalized = self.normalize_settings(current_settings) |
| 207 |
desired_normalized = self.normalize_settings(desired_settings) |
| 208 |
|
| 209 |
# For debugging version compatibility issues |
| 210 |
if self.module._verbosity >= 3: # Only show at high verbosity |
| 211 |
self.module.log(f"Current settings (normalized): {current_normalized}") |
| 212 |
self.module.log(f"Desired settings (normalized): {desired_normalized}") |
| 213 |
|
| 214 |
return current_normalized != desired_normalized |
| 215 |
|
| 216 |
def create(self): |
| 217 |
if not self.exists: |
| 218 |
query = "CREATE ROLE %s" % self.name |
| 219 |
|
| 220 |
if self.module.params['cluster']: |
| 221 |
query += " ON CLUSTER %s" % self.module.params['cluster'] |
| 222 |
|
| 223 |
list_settings = self.module.params['settings'] |
| 224 |
if list_settings: |
| 225 |
query += " SETTINGS" |
| 226 |
for index, value in enumerate(list_settings): |
| 227 |
query += " %s" % value |
| 228 |
if index < len(list_settings) - 1: |
| 229 |
query += "," |
| 230 |
|
| 231 |
executed_statements.append(query) |
| 232 |
|
| 233 |
if not self.module.check_mode: |
| 234 |
execute_query(self.module, self.client, query) |
| 235 |
|
| 236 |
self.exists = True |
| 237 |
return True |
| 238 |
else: |
| 239 |
return False |
| 240 |
|
| 241 |
def alter(self, settings): |
| 242 |
"""Update role settings using ALTER ROLE""" |
| 243 |
if not self.exists: |
| 244 |
return False |
| 245 |
|
| 246 |
query = "ALTER ROLE %s" % self.name |
| 247 |
|
| 248 |
if self.module.params['cluster']: |
| 249 |
query += " ON CLUSTER %s" % self.module.params['cluster'] |
| 250 |
|
| 251 |
# Handle settings updates |
| 252 |
if settings is not None and len(settings) > 0: |
| 253 |
# Set these settings |
| 254 |
query += " SETTINGS" |
| 255 |
for index, value in enumerate(settings): |
| 256 |
query += " %s" % value |
| 257 |
if index < len(settings) - 1: |
| 258 |
query += "," |
| 259 |
|
| 260 |
executed_statements.append(query) |
| 261 |
|
| 262 |
if not self.module.check_mode: |
| 263 |
execute_query(self.module, self.client, query) |
| 264 |
|
| 265 |
return True |
| 266 |
|
| 267 |
def drop(self): |
| 268 |
if self.exists: |
| 269 |
query = "DROP ROLE %s" % self.name |
| 270 |
executed_statements.append(query) |
| 271 |
|
| 272 |
if not self.module.check_mode: |
| 273 |
execute_query(self.module, self.client, query) |
| 274 |
|
| 275 |
self.exists = False |
| 276 |
return True |
| 277 |
else: |
| 278 |
return False |
| 279 |
|
| 280 |
|
| 281 |
def main(): |
| 282 |
# Set up arguments. |
| 283 |
# If there are common arguments shared across several modules, |
| 284 |
# create the common_argument_spec() function under plugins/module_utils/* |
| 285 |
# and invoke here to return a dict with those arguments |
| 286 |
argument_spec = client_common_argument_spec() |
| 287 |
argument_spec.update( |
| 288 |
state=dict(type="str", choices=["present", "absent"], default="present"), |
| 289 |
name=dict(type="str", required=True), |
| 290 |
cluster=dict(type='str', default=None), |
| 291 |
settings=dict(type='list', elements='str'), |
| 292 |
) |
| 293 |
|
| 294 |
# Instantiate an object of module class |
| 295 |
module = AnsibleModule( |
| 296 |
argument_spec=argument_spec, |
| 297 |
supports_check_mode=True, |
| 298 |
) |
| 299 |
|
| 300 |
# Assign passed options to variables |
| 301 |
client_kwargs = module.params["client_kwargs"] |
| 302 |
# The reason why these arguments are separate from client_kwargs |
| 303 |
# is that we need to protect some sensitive data like passwords passed |
| 304 |
# to the module from logging (see the arguments above with no_log=True); |
| 305 |
# Such data must be passed as module arguments (not nested deep in values). |
| 306 |
main_conn_kwargs = get_main_conn_kwargs(module) |
| 307 |
state = module.params["state"] |
| 308 |
name = module.params["name"] |
| 309 |
|
| 310 |
# Will fail if no driver informing the user |
| 311 |
check_clickhouse_driver(module) |
| 312 |
|
| 313 |
# Connect to DB |
| 314 |
client = connect_to_db_via_client(module, main_conn_kwargs, client_kwargs) |
| 315 |
|
| 316 |
# Do the job |
| 317 |
changed = False |
| 318 |
role = ClickHouseRole(module, client, name) |
| 319 |
desired_settings = module.params.get("settings", []) |
| 320 |
|
| 321 |
if state == "present": |
| 322 |
if not role.exists: |
| 323 |
# Role doesn't exist, create it |
| 324 |
changed = role.create() |
| 325 |
else: |
| 326 |
# Role exists, check if settings need to be updated |
| 327 |
if desired_settings is not None and len(desired_settings) > 0: # Only check settings if they are specified and not empty |
| 328 |
current_definition = role.get_current_role_definition() |
| 329 |
current_settings = role.parse_settings_from_create_statement(current_definition) if current_definition else [] |
| 330 |
|
| 331 |
if role.settings_changed(current_settings, desired_settings): |
| 332 |
changed = role.alter(desired_settings) |
| 333 |
else: |
| 334 |
# If state is absent |
| 335 |
if role.exists: |
| 336 |
changed = role.drop() |
| 337 |
|
| 338 |
# Close connection |
| 339 |
client.disconnect_connection() |
| 340 |
|
| 341 |
# Users will get this in JSON output after execution |
| 342 |
module.exit_json(changed=changed, executed_statements=executed_statements) |
| 343 |
|
| 344 |
|
| 345 |
if __name__ == "__main__": |
| 346 |
main() |