Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_mysql_users.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2017, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7 __metaclass__ = type
8
9 DOCUMENTATION = '''
10 ---
11 module: proxysql_mysql_users
12 author: "Ben Mildren (@bmildren)"
13 short_description: Adds or removes mysql users from proxysql admin interface
14 description:
15 - The M(community.proxysql.proxysql_mysql_users) module adds or removes mysql users using the
16 proxysql admin interface.
17 options:
18 username:
19 description:
20 - Name of the user connecting to the mysqld or ProxySQL instance.
21 type: str
22 required: true
23 password:
24 description:
25 - Password of the user connecting to the mysqld or ProxySQL instance.
26 type: str
27 encrypt_password:
28 description:
29 - Encrypt a cleartext password passed in the I(password) option, using
30 the method defined in I(encryption_method).
31 default: false
32 type: bool
33 encryption_method:
34 description:
35 - Encryption method used when I(encrypt_password) is set to C(True).
36 type: str
37 choices: [ "mysql_native_password", "caching_sha2_password" ]
38 default: mysql_native_password
39 salt:
40 description:
41 - Salt used when I(encryption_method) is set to C(caching_sha2_password).
42 If omitted the I(salt) is a randomly generated string and will change
43 value in ProxySQL database on each execution.
44 type: str
45 version_added: 1.7.0
46 active:
47 description:
48 - A user with I(active) set to C(False) will be tracked in the database,
49 but will be never loaded in the in-memory data structures. If omitted
50 the proxysql database default for I(active) is C(True).
51 type: bool
52 use_ssl:
53 description:
54 - If I(use_ssl) is set to C(True), connections by this user will be made
55 using SSL connections. If omitted the proxysql database default for
56 I(use_ssl) is C(False).
57 type: bool
58 default_hostgroup:
59 description:
60 - If there is no matching rule for the queries sent by this user, the
61 traffic it generates is sent to the specified hostgroup.
62 If omitted the proxysql database default for I(use_ssl) is 0.
63 type: int
64 default_schema:
65 description:
66 - The schema to which the connection should change to by default.
67 type: str
68 transaction_persistent:
69 description:
70 - If this is set for the user with which the MySQL client is connecting
71 to ProxySQL (thus a "frontend" user), transactions started within a
72 hostgroup will remain within that hostgroup regardless of any other
73 rules.
74 If omitted the proxysql database default for I(transaction_persistent)
75 is C(False).
76 type: bool
77 fast_forward:
78 description:
79 - If I(fast_forward) is set to C(True), I(fast_forward) will bypass the
80 query processing layer (rewriting, caching) and pass through the query
81 directly as is to the backend server. If omitted the proxysql database
82 default for I(fast_forward) is C(False).
83 type: bool
84 backend:
85 description:
86 - If I(backend) is set to C(True), this (username, password) pair is
87 used for authenticating to the ProxySQL instance.
88 default: true
89 type: bool
90 frontend:
91 description:
92 - If I(frontend) is set to C(True), this (username, password) pair is
93 used for authenticating to the mysqld servers against any hostgroup.
94 default: true
95 type: bool
96 max_connections:
97 description:
98 - The maximum number of connections ProxySQL will open to the backend for
99 this user. If omitted the proxysql database default for
100 I(max_connections) is 10000.
101 type: int
102 state:
103 description:
104 - When C(present) - adds the user, when C(absent) - removes the user.
105 type: str
106 choices: [ "present", "absent" ]
107 default: present
108 extends_documentation_fragment:
109 - community.proxysql.proxysql.managing_config
110 - community.proxysql.proxysql.connectivity
111 notes:
112 - Supports C(check_mode).
113 '''
114
115 EXAMPLES = '''
116 ---
117 # This example adds a user, it saves the mysql user config to disk, but
118 # avoids loading the mysql user config to runtime (this might be because
119 # several users are being added and the user wants to push the config to
120 # runtime in a single batch using the community.general.proxysql_manage_config
121 # module). It uses supplied credentials to connect to the proxysql admin
122 # interface.
123
124 - name: Add a user
125 community.proxysql.proxysql_mysql_users:
126 login_user: 'admin'
127 login_password: 'admin'
128 username: 'productiondba'
129 salt: 'secrets_of_20_chars_'
130 state: present
131 load_to_runtime: false
132
133 # This example removes a user, saves the mysql user config to disk, and
134 # dynamically loads the mysql user config to runtime. It uses credentials
135 # in a supplied config file to connect to the proxysql admin interface.
136
137 - name: Remove a user
138 community.proxysql.proxysql_mysql_users:
139 config_file: '~/proxysql.cnf'
140 username: 'mysqlboy'
141 state: absent
142 '''
143
144 RETURN = '''
145 stdout:
146 description: The mysql user modified or removed from proxysql.
147 returned: On create/update will return the newly modified user, on delete
148 it will return the deleted record.
149 type: dict
150 sample:
151 changed: true
152 msg: Added user to mysql_users
153 state: present
154 user:
155 active: 1
156 backend: 1
157 default_hostgroup: 1
158 default_schema: null
159 fast_forward: 0
160 frontend: 1
161 max_connections: 10000
162 password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
163 schema_locked: 0
164 transaction_persistent: 0
165 use_ssl: 0
166 username: guest_ro
167 username: guest_ro
168 '''
169
170 from ansible.module_utils.basic import AnsibleModule
171 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
172 mysql_connect,
173 mysql_driver,
174 proxysql_common_argument_spec,
175 save_config_to_disk,
176 load_config_to_runtime,
177 mysql_sha256_password_hash,
178 generate_random_salt,
179 )
180 from ansible.module_utils._text import to_native, to_bytes
181 from hashlib import sha1
182
183 # ===========================================
184 # proxysql module specific support methods.
185 #
186
187
188 def _mysql_native_password(cleartext_password, salt=None):
189 mysql_native_encrypted_password = "*" + sha1(sha1(to_bytes(cleartext_password)).digest()).hexdigest().upper()
190 return mysql_native_encrypted_password
191
192
193 def _caching_sha2_password(cleartext_password, salt):
194 if salt is None:
195 salt = generate_random_salt()
196
197 mysql_caching_sha2_password = mysql_sha256_password_hash(password=cleartext_password, salt=salt)
198 return mysql_caching_sha2_password
199
200
201 def encrypt_cleartext_password(password_to_encrypt, encryption_method, salt):
202 encrypted_password = encryption_method(password_to_encrypt, salt)
203 return encrypted_password
204
205
206 encryption_method_map = {
207 'mysql_native_password': _mysql_native_password,
208 'caching_sha2_password': _caching_sha2_password
209 }
210
211
212 class ProxySQLUser(object):
213
214 def __init__(self, module):
215 self.state = module.params["state"]
216 self.save_to_disk = module.params["save_to_disk"]
217 self.load_to_runtime = module.params["load_to_runtime"]
218
219 self.username = module.params["username"]
220 self.backend = module.params["backend"]
221 self.frontend = module.params["frontend"]
222 self.salt = module.params["salt"]
223
224 config_data_keys = ["password",
225 "active",
226 "use_ssl",
227 "default_hostgroup",
228 "default_schema",
229 "transaction_persistent",
230 "fast_forward",
231 "max_connections"
232 ]
233
234 self.config_data = dict((k, module.params[k])
235 for k in config_data_keys)
236
237 if module.params["password"] is not None and module.params["encrypt_password"]:
238 encryption_method = encryption_method_map[module.params["encryption_method"]]
239 salt = module.params["salt"]
240 encrypted_password = encrypt_cleartext_password(module.params["password"], encryption_method, salt)
241 self.config_data["password"] = encrypted_password
242
243 def check_user_config_exists(self, cursor):
244 query_string = \
245 """SELECT count(*) AS `user_count`
246 FROM mysql_users
247 WHERE username = %s
248 AND backend = %s
249 AND frontend = %s"""
250
251 query_data = \
252 [self.username,
253 self.backend,
254 self.frontend]
255
256 cursor.execute(query_string, query_data)
257 check_count = cursor.fetchone()
258 return (int(check_count['user_count']) > 0)
259
260 def check_user_privs(self, cursor):
261 query_string = \
262 """SELECT count(*) AS `user_count`
263 FROM mysql_users
264 WHERE username = %s
265 AND backend = %s
266 AND frontend = %s"""
267
268 query_data = \
269 [self.username,
270 self.backend,
271 self.frontend]
272
273 for col, val in self.config_data.items():
274 if val is not None:
275 query_data.append(val)
276 query_string += "\n AND " + col + " = %s"
277
278 cursor.execute(query_string, query_data)
279 check_count = cursor.fetchone()
280 return (int(check_count['user_count']) > 0)
281
282 def get_user_config(self, cursor):
283 query_string = \
284 """SELECT *
285 FROM mysql_users
286 WHERE username = %s
287 AND backend = %s
288 AND frontend = %s"""
289
290 query_data = \
291 [self.username,
292 self.backend,
293 self.frontend]
294
295 cursor.execute(query_string, query_data)
296 user = cursor.fetchone()
297 return user
298
299 def create_user_config(self, cursor):
300 query_string = \
301 """INSERT INTO mysql_users (
302 username,
303 backend,
304 frontend"""
305
306 cols = 3
307 query_data = \
308 [self.username,
309 self.backend,
310 self.frontend]
311
312 for col, val in self.config_data.items():
313 if val is not None:
314 cols += 1
315 query_data.append(val)
316 query_string += ",\n" + col
317
318 query_string += \
319 (")\n" +
320 "VALUES (" +
321 "%s ," * cols)
322
323 query_string = query_string[:-2]
324 query_string += ")"
325
326 cursor.execute(query_string, query_data)
327 return True
328
329 def update_user_config(self, cursor):
330 query_string = """UPDATE mysql_users"""
331
332 cols = 0
333 query_data = []
334
335 for col, val in self.config_data.items():
336 if val is not None:
337 cols += 1
338 query_data.append(val)
339 if cols == 1:
340 query_string += "\nSET " + col + "= %s,"
341 else:
342 query_string += "\n " + col + " = %s,"
343
344 query_string = query_string[:-1]
345 query_string += ("\nWHERE username = %s\n AND backend = %s" +
346 "\n AND frontend = %s")
347
348 query_data.append(self.username)
349 query_data.append(self.backend)
350 query_data.append(self.frontend)
351
352 cursor.execute(query_string, query_data)
353 return True
354
355 def delete_user_config(self, cursor):
356 query_string = \
357 """DELETE FROM mysql_users
358 WHERE username = %s
359 AND backend = %s
360 AND frontend = %s"""
361
362 query_data = \
363 [self.username,
364 self.backend,
365 self.frontend]
366
367 cursor.execute(query_string, query_data)
368 return True
369
370 def manage_config(self, cursor, state):
371 if state:
372 if self.save_to_disk:
373 save_config_to_disk(cursor, "USERS")
374 if self.load_to_runtime:
375 load_config_to_runtime(cursor, "USERS")
376
377 def create_user(self, check_mode, result, cursor):
378 if not check_mode:
379 result['changed'] = \
380 self.create_user_config(cursor)
381 result['msg'] = "Added user to mysql_users"
382 result['user'] = \
383 self.get_user_config(cursor)
384 self.manage_config(cursor,
385 result['changed'])
386 else:
387 result['changed'] = True
388 result['msg'] = ("User would have been added to" +
389 " mysql_users, however check_mode" +
390 " is enabled.")
391
392 def update_user(self, check_mode, result, cursor):
393 if not check_mode:
394 result['changed'] = \
395 self.update_user_config(cursor)
396 result['msg'] = "Updated user in mysql_users"
397 result['user'] = \
398 self.get_user_config(cursor)
399 self.manage_config(cursor,
400 result['changed'])
401 else:
402 result['changed'] = True
403 result['msg'] = ("User would have been updated in" +
404 " mysql_users, however check_mode" +
405 " is enabled.")
406
407 def delete_user(self, check_mode, result, cursor):
408 if not check_mode:
409 result['user'] = \
410 self.get_user_config(cursor)
411 result['changed'] = \
412 self.delete_user_config(cursor)
413 result['msg'] = "Deleted user from mysql_users"
414 self.manage_config(cursor,
415 result['changed'])
416 else:
417 result['changed'] = True
418 result['msg'] = ("User would have been deleted from" +
419 " mysql_users, however check_mode is" +
420 " enabled.")
421
422 # ===========================================
423 # Module execution.
424 #
425
426
427 def main():
428 argument_spec = proxysql_common_argument_spec()
429 argument_spec.update(
430 username=dict(required=True, type='str'),
431 password=dict(no_log=True, type='str'),
432 salt=dict(no_log=True, type='str'),
433 encrypt_password=dict(default=False, type='bool', no_log=False),
434 encryption_method=dict(default='mysql_native_password', choices=list(encryption_method_map.keys())),
435 active=dict(type='bool'),
436 use_ssl=dict(type='bool'),
437 default_hostgroup=dict(type='int'),
438 default_schema=dict(type='str'),
439 transaction_persistent=dict(type='bool'),
440 fast_forward=dict(type='bool'),
441 backend=dict(default=True, type='bool'),
442 frontend=dict(default=True, type='bool'),
443 max_connections=dict(type='int'),
444 state=dict(default='present', choices=['present',
445 'absent']),
446 save_to_disk=dict(default=True, type='bool'),
447 load_to_runtime=dict(default=True, type='bool')
448 )
449
450 module = AnsibleModule(
451 supports_check_mode=True,
452 argument_spec=argument_spec
453 )
454
455 login_user = module.params["login_user"]
456 login_password = module.params["login_password"]
457 config_file = module.params["config_file"]
458
459 cursor = None
460 try:
461 cursor, db_conn, version = mysql_connect(module,
462 login_user,
463 login_password,
464 config_file,
465 cursor_class='DictCursor')
466 except mysql_driver.Error as e:
467 module.fail_json(
468 msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)
469 )
470
471 proxysql_user = ProxySQLUser(module)
472 result = {}
473
474 result['state'] = proxysql_user.state
475 if proxysql_user.username:
476 result['username'] = proxysql_user.username
477
478 if proxysql_user.state == "present":
479 try:
480 if not proxysql_user.check_user_privs(cursor):
481 if not proxysql_user.check_user_config_exists(cursor):
482 proxysql_user.create_user(module.check_mode,
483 result,
484 cursor)
485 else:
486 proxysql_user.update_user(module.check_mode,
487 result,
488 cursor)
489 else:
490 result['changed'] = False
491 result['msg'] = ("The user already exists in mysql_users" +
492 " and doesn't need to be updated.")
493 result['user'] = \
494 proxysql_user.get_user_config(cursor)
495 except mysql_driver.Error as e:
496 module.fail_json(
497 msg="unable to modify user.. %s" % to_native(e)
498 )
499
500 elif proxysql_user.state == "absent":
501 try:
502 if proxysql_user.check_user_config_exists(cursor):
503 proxysql_user.delete_user(module.check_mode,
504 result,
505 cursor)
506 else:
507 result['changed'] = False
508 result['msg'] = ("The user is already absent from the" +
509 " mysql_users memory configuration")
510 except mysql_driver.Error as e:
511 module.fail_json(
512 msg="unable to remove user.. %s" % to_native(e)
513 )
514
515 module.exit_json(**result)
516
517
518 if __name__ == '__main__':
519 main()