def main(): argument_spec = mysql_common_argument_spec() argument_spec.update( login_db=dict(type='str'), filter=dict(type='list'), exclude_fields=dict(type='list'), return_empty_dbs=dict(type='bool', default=False), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) db = module.params['login_db'] connect_timeout = module.params['connect_timeout'] login_user = module.params['login_user'] login_password = module.params['login_password'] ssl_cert = module.params['client_cert'] ssl_key = module.params['client_key'] ssl_ca = module.params['ca_cert'] config_file = module.params['config_file'] filter_ = module.params['filter'] exclude_fields = module.params['exclude_fields'] return_empty_dbs = module.params['return_empty_dbs'] if filter_: filter_ = [f.strip() for f in filter_] if exclude_fields: exclude_fields = set([f.strip() for f in exclude_fields]) if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, db, connect_timeout=connect_timeout, cursor_class='DictCursor') except Exception as e: module.fail_json( msg= "unable to connect to database, check login_user and login_password are correct or %s has the credentials. " "Exception message: %s" % (config_file, to_native(e))) ############################### # Create object and do main job mysql = MySQL_Info(module, cursor) module.exit_json(changed=False, **mysql.get_info(filter_, exclude_fields, return_empty_dbs))
def main(): module = AnsibleModule(argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default="", type='path'), action=dict(required=True, choices=['LOAD', 'SAVE']), config_settings=dict(required=True, choices=[ 'MYSQL USERS', 'MYSQL SERVERS', 'MYSQL QUERY RULES', 'MYSQL VARIABLES', 'ADMIN VARIABLES', 'SCHEDULER' ]), direction=dict(required=True, choices=['FROM', 'TO']), config_layer=dict(required=True, choices=['MEMORY', 'DISK', 'RUNTIME', 'CONFIG'])), supports_check_mode=True) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] action = module.params["action"] config_settings = module.params["config_settings"] direction = module.params["direction"] config_layer = module.params["config_layer"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file) except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)) result = {} manage_config_settings = \ [action, config_settings, direction, config_layer] try: result['changed'] = manage_config(manage_config_settings, cursor) except mysql_driver.Error as e: module.fail_json(msg="unable to manage config.. %s" % to_native(e)) module.exit_json(**result)
def main(): module = AnsibleModule(argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default='', type='path'), username=dict(required=True, type='str'), password=dict(no_log=True, type='str'), active=dict(type='bool'), use_ssl=dict(type='bool'), default_hostgroup=dict(type='int'), default_schema=dict(type='str'), transaction_persistent=dict(type='bool'), fast_forward=dict(type='bool'), backend=dict(default=True, type='bool'), frontend=dict(default=True, type='bool'), max_connections=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool')), supports_check_mode=True) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor, db_conn = mysql_connect( module, login_user, login_password, config_file, cursor_class=mysql_driver.cursors.DictCursor) except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)) proxysql_user = ProxySQLUser(module) result = {} result['state'] = proxysql_user.state if proxysql_user.username: result['username'] = proxysql_user.username if proxysql_user.state == "present": try: if not proxysql_user.check_user_privs(cursor): if not proxysql_user.check_user_config_exists(cursor): proxysql_user.create_user(module.check_mode, result, cursor) else: proxysql_user.update_user(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The user already exists in mysql_users" + " and doesn't need to be updated.") result['user'] = \ proxysql_user.get_user_config(cursor) except mysql_driver.Error as e: module.fail_json(msg="unable to modify user.. %s" % to_native(e)) elif proxysql_user.state == "absent": try: if proxysql_user.check_user_config_exists(cursor): proxysql_user.delete_user(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The user is already absent from the" + " mysql_users memory configuration") except mysql_driver.Error as e: module.fail_json(msg="unable to remove user.. %s" % to_native(e)) module.exit_json(**result)
def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(type='str'), login_password=dict(type='str', no_log=True), login_host=dict(type='str', default='localhost'), login_port=dict(type='int', default=3306), login_unix_socket=dict(type='str'), user=dict(type='str', required=True, aliases=['name']), password=dict(type='str', no_log=True), encrypted=dict(type='bool', default=False), host=dict(type='str', default='localhost'), host_all=dict(type="bool", default=False), state=dict(type='str', default='present', choices=['absent', 'present']), priv=dict(type='raw'), append_privs=dict(type='bool', default=False), check_implicit_admin=dict(type='bool', default=False), update_password=dict(type='str', default='always', choices=['always', 'on_create'], no_log=False), connect_timeout=dict(type='int', default=30), config_file=dict(type='path', default='~/.my.cnf'), sql_log_bin=dict(type='bool', default=True), client_cert=dict(type='path', aliases=['ssl_cert']), client_key=dict(type='path', aliases=['ssl_key']), ca_cert=dict(type='path', aliases=['ssl_ca']), plugin=dict(default=None, type='str'), plugin_hash_string=dict(default=None, type='str'), plugin_auth_string=dict(default=None, type='str'), ), supports_check_mode=True, ) login_user = module.params["login_user"] login_password = module.params["login_password"] user = module.params["user"] password = module.params["password"] encrypted = module.boolean(module.params["encrypted"]) host = module.params["host"].lower() host_all = module.params["host_all"] state = module.params["state"] priv = module.params["priv"] check_implicit_admin = module.params['check_implicit_admin'] connect_timeout = module.params['connect_timeout'] config_file = module.params['config_file'] append_privs = module.boolean(module.params["append_privs"]) update_password = module.params['update_password'] ssl_cert = module.params["client_cert"] ssl_key = module.params["client_key"] ssl_ca = module.params["ca_cert"] db = '' sql_log_bin = module.params["sql_log_bin"] plugin = module.params["plugin"] plugin_hash_string = module.params["plugin_hash_string"] plugin_auth_string = module.params["plugin_auth_string"] if priv and not (isinstance(priv, str) or isinstance(priv, dict)): module.fail_json( msg="priv parameter must be str or dict but %s was passed" % type(priv)) if priv and isinstance(priv, dict): priv = convert_priv_dict_to_str(priv) if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) cursor = None try: if check_implicit_admin: try: cursor, db_conn = mysql_connect( module, 'root', '', config_file, ssl_cert, ssl_key, ssl_ca, db, connect_timeout=connect_timeout) except Exception: pass if not cursor: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, db, connect_timeout=connect_timeout) except Exception as e: module.fail_json( msg= "unable to connect to database, check login_user and login_password are correct or %s has the credentials. " "Exception message: %s" % (config_file, to_native(e))) if not sql_log_bin: cursor.execute("SET SQL_LOG_BIN=0;") if priv is not None: try: mode = get_mode(cursor) except Exception as e: module.fail_json(msg=to_native(e)) try: priv = privileges_unpack(priv, mode) except Exception as e: module.fail_json(msg="invalid privileges string: %s" % to_native(e)) if state == "present": if user_exists(cursor, user, host, host_all): try: if update_password == 'always': changed, msg = user_mod(cursor, user, host, host_all, password, encrypted, plugin, plugin_hash_string, plugin_auth_string, priv, append_privs, module) else: changed, msg = user_mod(cursor, user, host, host_all, None, encrypted, plugin, plugin_hash_string, plugin_auth_string, priv, append_privs, module) except (SQLParseError, InvalidPrivsError, mysql_driver.Error) as e: module.fail_json(msg=to_native(e)) else: if host_all: module.fail_json( msg="host_all parameter cannot be used when adding a user") try: changed = user_add(cursor, user, host, host_all, password, encrypted, plugin, plugin_hash_string, plugin_auth_string, priv, module.check_mode) if changed: msg = "User added" except (SQLParseError, InvalidPrivsError, mysql_driver.Error) as e: module.fail_json(msg=to_native(e)) elif state == "absent": if user_exists(cursor, user, host, host_all): changed = user_delete(cursor, user, host, host_all, module.check_mode) msg = "User deleted" else: changed = False msg = "User doesn't exist" module.exit_json(changed=changed, user=user, msg=msg)
def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(type='str'), login_password=dict(type='str', no_log=True), login_host=dict(type='str', default='localhost'), login_port=dict(type='int', default=3306), login_unix_socket=dict(type='str'), name=dict(type='list', required=True, aliases=['db']), encoding=dict(type='str', default=''), collation=dict(type='str', default=''), target=dict(type='path'), state=dict(type='str', default='present', choices=['absent', 'dump', 'import', 'present']), client_cert=dict(type='path', aliases=['ssl_cert']), client_key=dict(type='path', aliases=['ssl_key']), ca_cert=dict(type='path', aliases=['ssl_ca']), connect_timeout=dict(type='int', default=30), config_file=dict(type='path', default='~/.my.cnf'), single_transaction=dict(type='bool', default=False), quick=dict(type='bool', default=True), ignore_tables=dict(type='list', default=[]), hex_blob=dict(default=False, type='bool'), force=dict(type='bool', default=False), master_data=dict(type='int', default=0, choices=[0, 1, 2]), skip_lock_tables=dict(type='bool', default=False), dump_extra_args=dict(type='str'), use_shell=dict(type='bool', default=False), unsafe_login_password=dict(type='bool', default=False), restrict_config_file=dict(type='bool', default=False), ), supports_check_mode=True, ) if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) db = module.params["name"] if not db: module.exit_json(changed=False, db=db, db_list=[]) db = [each_db.strip() for each_db in db] encoding = module.params["encoding"] collation = module.params["collation"] state = module.params["state"] target = module.params["target"] socket = module.params["login_unix_socket"] login_port = module.params["login_port"] if login_port < 0 or login_port > 65535: module.fail_json( msg="login_port must be a valid unix port number (0-65535)") ssl_cert = module.params["client_cert"] ssl_key = module.params["client_key"] ssl_ca = module.params["ca_cert"] connect_timeout = module.params['connect_timeout'] config_file = module.params['config_file'] login_password = module.params["login_password"] unsafe_login_password = module.params["unsafe_login_password"] login_user = module.params["login_user"] login_host = module.params["login_host"] ignore_tables = module.params["ignore_tables"] for a_table in ignore_tables: if a_table == "": module.fail_json(msg="Name of ignored table cannot be empty") single_transaction = module.params["single_transaction"] quick = module.params["quick"] hex_blob = module.params["hex_blob"] force = module.params["force"] master_data = module.params["master_data"] skip_lock_tables = module.params["skip_lock_tables"] dump_extra_args = module.params["dump_extra_args"] use_shell = module.params["use_shell"] restrict_config_file = module.params["restrict_config_file"] if len(db) > 1 and state == 'import': module.fail_json( msg="Multiple databases are not supported with state=import") db_name = ' '.join(db) all_databases = False if state in ['dump', 'import']: if target is None: module.fail_json(msg="with state=%s target is required" % state) if db == ['all']: all_databases = True else: if db == ['all']: module.fail_json( msg= "name is not allowed to equal 'all' unless state equals import, or dump." ) try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, connect_timeout=connect_timeout) except Exception as e: if os.path.exists(config_file): module.fail_json( msg= "unable to connect to database, check login_user and login_password are correct or %s has the credentials. " "Exception message: %s" % (config_file, to_native(e))) else: module.fail_json(msg="unable to find %s. Exception message: %s" % (config_file, to_native(e))) changed = False if not os.path.exists(config_file): config_file = None existence_list = [] non_existence_list = [] if not all_databases: for each_database in db: if db_exists(cursor, [each_database]): existence_list.append(each_database) else: non_existence_list.append(each_database) if state == "absent": if module.check_mode: module.exit_json(changed=bool(existence_list), db=db_name, db_list=db) try: changed = db_delete(cursor, existence_list) except Exception as e: module.fail_json(msg="error deleting database: %s" % to_native(e)) module.exit_json(changed=changed, db=db_name, db_list=db, executed_commands=executed_commands) elif state == "present": if module.check_mode: module.exit_json(changed=bool(non_existence_list), db=db_name, db_list=db) changed = False if non_existence_list: try: changed = db_create(cursor, non_existence_list, encoding, collation) except Exception as e: module.fail_json(msg="error creating database: %s" % to_native(e), exception=traceback.format_exc()) module.exit_json(changed=changed, db=db_name, db_list=db, executed_commands=executed_commands) elif state == "dump": if non_existence_list and not all_databases: module.fail_json(msg="Cannot dump database(s) %r - not found" % (', '.join(non_existence_list))) if module.check_mode: module.exit_json(changed=True, db=db_name, db_list=db) rc, stdout, stderr = db_dump( module, login_host, login_user, login_password, db, target, all_databases, login_port, config_file, socket, ssl_cert, ssl_key, ssl_ca, single_transaction, quick, ignore_tables, hex_blob, encoding, force, master_data, skip_lock_tables, dump_extra_args, unsafe_login_password, restrict_config_file) if rc != 0: module.fail_json(msg="%s" % stderr) module.exit_json(changed=True, db=db_name, db_list=db, msg=stdout, executed_commands=executed_commands) elif state == "import": if module.check_mode: module.exit_json(changed=True, db=db_name, db_list=db) if non_existence_list and not all_databases: try: db_create(cursor, non_existence_list, encoding, collation) except Exception as e: module.fail_json(msg="error creating database: %s" % to_native(e), exception=traceback.format_exc()) rc, stdout, stderr = db_import( module, login_host, login_user, login_password, db, target, all_databases, login_port, config_file, socket, ssl_cert, ssl_key, ssl_ca, encoding, force, use_shell, unsafe_login_password, restrict_config_file) if rc != 0: module.fail_json(msg="%s" % stderr) module.exit_json(changed=True, db=db_name, db_list=db, msg=stdout, executed_commands=executed_commands)
def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(type='str'), login_password=dict(type='str', no_log=True), login_host=dict(type='str', default='localhost'), login_port=dict(type='int', default=3306), login_unix_socket=dict(type='str'), variable=dict(type='str'), value=dict(type='str'), client_cert=dict(type='path', aliases=['ssl_cert']), client_key=dict(type='path', aliases=['ssl_key']), ca_cert=dict(type='path', aliases=['ssl_ca']), connect_timeout=dict(type='int', default=30), config_file=dict(type='path', default='~/.my.cnf'), mode=dict(type='str', choices=['global', 'persist', 'persist_only'], default='global'), ), ) user = module.params["login_user"] password = module.params["login_password"] connect_timeout = module.params['connect_timeout'] ssl_cert = module.params["client_cert"] ssl_key = module.params["client_key"] ssl_ca = module.params["ca_cert"] config_file = module.params['config_file'] db = 'mysql' mysqlvar = module.params["variable"] value = module.params["value"] mode = module.params["mode"] if mysqlvar is None: module.fail_json(msg="Cannot run without variable to operate with") if match('^[0-9a-z_.]+$', mysqlvar) is None: module.fail_json(msg="invalid variable name \"%s\"" % mysqlvar) if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) else: warnings.filterwarnings('error', category=mysql_driver.Warning) try: cursor, db_conn = mysql_connect(module, user, password, config_file, ssl_cert, ssl_key, ssl_ca, db, connect_timeout=connect_timeout) except Exception as e: if os.path.exists(config_file): module.fail_json(msg=("unable to connect to database, check login_user and " "login_password are correct or %s has the credentials. " "Exception message: %s" % (config_file, to_native(e)))) else: module.fail_json(msg="unable to find %s. Exception message: %s" % (config_file, to_native(e))) mysqlvar_val = None var_in_mysqld_auto_cnf = None mysqlvar_val = getvariable(cursor, mysqlvar) if mysqlvar_val is None: module.fail_json(msg="Variable not available \"%s\"" % mysqlvar, changed=False) if value is None: module.exit_json(msg=mysqlvar_val) if mode in ('persist', 'persist_only'): var_in_mysqld_auto_cnf = check_mysqld_auto(module, cursor, mysqlvar) if mode == 'persist_only': if var_in_mysqld_auto_cnf is None: mysqlvar_val = False else: mysqlvar_val = var_in_mysqld_auto_cnf # Type values before using them value_wanted = typedvalue(value) value_actual = typedvalue(mysqlvar_val) value_in_auto_cnf = None if var_in_mysqld_auto_cnf is not None: value_in_auto_cnf = typedvalue(var_in_mysqld_auto_cnf) if value_wanted == value_actual and mode in ('global', 'persist'): if mode == 'persist' and value_wanted == value_in_auto_cnf: module.exit_json(msg="Variable is already set to requested value globally" "and stored into mysqld-auto.cnf file.", changed=False) elif mode == 'global': module.exit_json(msg="Variable is already set to requested value.", changed=False) if mode == 'persist_only' and value_wanted == value_in_auto_cnf: module.exit_json(msg="Variable is already stored into mysqld-auto.cnf " "with requested value.", changed=False) try: result = setvariable(cursor, mysqlvar, value_wanted, mode) except SQLParseError as e: result = to_native(e) if result is True: module.exit_json(msg="Variable change succeeded prev_value=%s" % value_actual, changed=True, queries=executed_queries) else: module.fail_json(msg=result, changed=False)
def main(): module = AnsibleModule(argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default="", type='path'), writer_hostgroup=dict(required=True, type='int'), reader_hostgroup=dict(required=True, type='int'), comment=dict(type='str'), state=dict(default='present', choices=['present', 'absent']), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool')), supports_check_mode=True) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, cursor_class='DictCursor') except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)) proxysql_repl_group = ProxySQLReplicationHostgroup(module) result = {} result['state'] = proxysql_repl_group.state if proxysql_repl_group.state == "present": try: if not proxysql_repl_group.check_repl_group_config(cursor, keys=True): proxysql_repl_group.create_repl_group(module.check_mode, result, cursor) else: if not proxysql_repl_group.check_repl_group_config(cursor, keys=False): proxysql_repl_group.update_repl_group( module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The repl group already exists in" + " mysql_replication_hostgroups and" + " doesn't need to be updated.") result['repl_group'] = \ proxysql_repl_group.get_repl_group_config(cursor) except mysql_driver.Error as e: module.fail_json( msg="unable to modify replication hostgroup.. %s" % to_native(e)) elif proxysql_repl_group.state == "absent": try: if proxysql_repl_group.check_repl_group_config(cursor, keys=True): proxysql_repl_group.delete_repl_group(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The repl group is already absent from the" + " mysql_replication_hostgroups memory" + " configuration") except mysql_driver.Error as e: module.fail_json( msg="unable to delete replication hostgroup.. %s" % to_native(e)) module.exit_json(**result)
def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(type='str'), login_password=dict(type='str', no_log=True), login_host=dict(type='str', default='localhost'), login_port=dict(type='int', default=3306), login_unix_socket=dict(type='str'), mode=dict(type='str', default='getslave', choices=[ 'getmaster', 'getslave', 'changemaster', 'stopslave', 'startslave', 'resetmaster', 'resetslave', 'resetslaveall']), master_auto_position=dict(type='bool', default=False), master_host=dict(type='str'), master_user=dict(type='str'), master_password=dict(type='str', no_log=True), master_port=dict(type='int'), master_connect_retry=dict(type='int'), master_log_file=dict(type='str'), master_log_pos=dict(type='int'), relay_log_file=dict(type='str'), relay_log_pos=dict(type='int'), master_ssl=dict(type='bool', default=False), master_ssl_ca=dict(type='str'), master_ssl_capath=dict(type='str'), master_ssl_cert=dict(type='str'), master_ssl_key=dict(type='str'), master_ssl_cipher=dict(type='str'), connect_timeout=dict(type='int', default=30), config_file=dict(type='path', default='~/.my.cnf'), client_cert=dict(type='path', aliases=['ssl_cert']), client_key=dict(type='path', aliases=['ssl_key']), ca_cert=dict(type='path', aliases=['ssl_ca']), master_use_gtid=dict(type='str', choices=['current_pos', 'slave_pos', 'disabled']), master_delay=dict(type='int'), connection_name=dict(type='str'), channel=dict(type='str'), fail_on_error=dict(type='bool', default=False), ), mutually_exclusive=[ ['connection_name', 'channel'] ], ) mode = module.params["mode"] master_host = module.params["master_host"] master_user = module.params["master_user"] master_password = module.params["master_password"] master_port = module.params["master_port"] master_connect_retry = module.params["master_connect_retry"] master_log_file = module.params["master_log_file"] master_log_pos = module.params["master_log_pos"] relay_log_file = module.params["relay_log_file"] relay_log_pos = module.params["relay_log_pos"] master_ssl = module.params["master_ssl"] master_ssl_ca = module.params["master_ssl_ca"] master_ssl_capath = module.params["master_ssl_capath"] master_ssl_cert = module.params["master_ssl_cert"] master_ssl_key = module.params["master_ssl_key"] master_ssl_cipher = module.params["master_ssl_cipher"] master_auto_position = module.params["master_auto_position"] ssl_cert = module.params["client_cert"] ssl_key = module.params["client_key"] ssl_ca = module.params["ca_cert"] connect_timeout = module.params['connect_timeout'] config_file = module.params['config_file'] master_delay = module.params['master_delay'] if module.params.get("master_use_gtid") == 'disabled': master_use_gtid = 'no' else: master_use_gtid = module.params["master_use_gtid"] connection_name = module.params["connection_name"] channel = module.params['channel'] fail_on_error = module.params['fail_on_error'] if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) else: warnings.filterwarnings('error', category=mysql_driver.Warning) login_password = module.params["login_password"] login_user = module.params["login_user"] try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, None, cursor_class='DictCursor', connect_timeout=connect_timeout) except Exception as e: if os.path.exists(config_file): module.fail_json(msg="unable to connect to database, check login_user and login_password are correct or %s has the credentials. " "Exception message: %s" % (config_file, to_native(e))) else: module.fail_json(msg="unable to find %s. Exception message: %s" % (config_file, to_native(e))) if mode in "getmaster": status = get_master_status(cursor) if not isinstance(status, dict): status = dict(Is_Master=False, msg="Server is not configured as mysql master") else: status['Is_Master'] = True module.exit_json(queries=executed_queries, **status) elif mode in "getslave": status = get_slave_status(cursor, connection_name, channel) if not isinstance(status, dict): status = dict(Is_Slave=False, msg="Server is not configured as mysql slave") else: status['Is_Slave'] = True module.exit_json(queries=executed_queries, **status) elif mode in "changemaster": chm = [] result = {} if master_host is not None: chm.append("MASTER_HOST='%s'" % master_host) if master_user is not None: chm.append("MASTER_USER='******'" % master_user) if master_password is not None: chm.append("MASTER_PASSWORD='******'" % master_password) if master_port is not None: chm.append("MASTER_PORT=%s" % master_port) if master_connect_retry is not None: chm.append("MASTER_CONNECT_RETRY=%s" % master_connect_retry) if master_log_file is not None: chm.append("MASTER_LOG_FILE='%s'" % master_log_file) if master_log_pos is not None: chm.append("MASTER_LOG_POS=%s" % master_log_pos) if master_delay is not None: chm.append("MASTER_DELAY=%s" % master_delay) if relay_log_file is not None: chm.append("RELAY_LOG_FILE='%s'" % relay_log_file) if relay_log_pos is not None: chm.append("RELAY_LOG_POS=%s" % relay_log_pos) if master_ssl: chm.append("MASTER_SSL=1") if master_ssl_ca is not None: chm.append("MASTER_SSL_CA='%s'" % master_ssl_ca) if master_ssl_capath is not None: chm.append("MASTER_SSL_CAPATH='%s'" % master_ssl_capath) if master_ssl_cert is not None: chm.append("MASTER_SSL_CERT='%s'" % master_ssl_cert) if master_ssl_key is not None: chm.append("MASTER_SSL_KEY='%s'" % master_ssl_key) if master_ssl_cipher is not None: chm.append("MASTER_SSL_CIPHER='%s'" % master_ssl_cipher) if master_auto_position: chm.append("MASTER_AUTO_POSITION=1") if master_use_gtid is not None: chm.append("MASTER_USE_GTID=%s" % master_use_gtid) try: changemaster(cursor, chm, connection_name, channel) except mysql_driver.Warning as e: result['warning'] = to_native(e) except Exception as e: module.fail_json(msg='%s. Query == CHANGE MASTER TO %s' % (to_native(e), chm)) result['changed'] = True module.exit_json(queries=executed_queries, **result) elif mode in "startslave": started = start_slave(module, cursor, connection_name, channel, fail_on_error) if started is True: module.exit_json(msg="Slave started ", changed=True, queries=executed_queries) else: module.exit_json(msg="Slave already started (Or cannot be started)", changed=False, queries=executed_queries) elif mode in "stopslave": stopped = stop_slave(module, cursor, connection_name, channel, fail_on_error) if stopped is True: module.exit_json(msg="Slave stopped", changed=True, queries=executed_queries) else: module.exit_json(msg="Slave already stopped", changed=False, queries=executed_queries) elif mode in "resetmaster": reset = reset_master(module, cursor, fail_on_error) if reset is True: module.exit_json(msg="Master reset", changed=True, queries=executed_queries) else: module.exit_json(msg="Master already reset", changed=False, queries=executed_queries) elif mode in "resetslave": reset = reset_slave(module, cursor, connection_name, channel, fail_on_error) if reset is True: module.exit_json(msg="Slave reset", changed=True, queries=executed_queries) else: module.exit_json(msg="Slave already reset", changed=False, queries=executed_queries) elif mode in "resetslaveall": reset = reset_slave_all(module, cursor, connection_name, channel, fail_on_error) if reset is True: module.exit_json(msg="Slave reset", changed=True, queries=executed_queries) else: module.exit_json(msg="Slave already reset", changed=False, queries=executed_queries) warnings.simplefilter("ignore")
def main(): module = AnsibleModule(argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default="", type='path'), active=dict(default=True, type='bool'), interval_ms=dict(default=10000, type='int'), filename=dict(required=True, type='str'), arg1=dict(type='str'), arg2=dict(type='str'), arg3=dict(type='str'), arg4=dict(type='str'), arg5=dict(type='str'), comment=dict(type='str'), state=dict(default='present', choices=['present', 'absent']), force_delete=dict(default=False, type='bool'), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool')), supports_check_mode=True) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, cursor_class='DictCursor') except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)) proxysql_schedule = ProxySQLSchedule(module) result = {} result['state'] = proxysql_schedule.state result['filename'] = proxysql_schedule.filename if proxysql_schedule.state == "present": try: if proxysql_schedule.check_schedule_config(cursor) <= 0: proxysql_schedule.create_schedule(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The schedule already exists and doesn't" + " need to be updated.") result['schedules'] = \ proxysql_schedule.get_schedule_config(cursor) except mysql_driver.Error as e: module.fail_json(msg="unable to modify schedule.. %s" % to_native(e)) elif proxysql_schedule.state == "absent": try: existing_schedules = \ proxysql_schedule.check_schedule_config(cursor) if existing_schedules > 0: if existing_schedules == 1 or proxysql_schedule.force_delete: proxysql_schedule.delete_schedule(module.check_mode, result, cursor) else: module.fail_json( msg=("Operation would delete multiple records" + " use force_delete to override this")) else: result['changed'] = False result['msg'] = ("The schedule is already absent from the" + " memory configuration") except mysql_driver.Error as e: module.fail_json(msg="unable to remove schedule.. %s" % to_native(e)) module.exit_json(**result)
def main(): module = AnsibleModule( argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default='127.0.0.1'), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default='', type='path'), hostgroup_id=dict(default=0, type='int'), hostname=dict(required=True, type='str'), port=dict(default=3306, type='int'), status=dict(choices=['ONLINE', 'OFFLINE_SOFT', 'OFFLINE_HARD']), weight=dict(type='int'), compression=dict(type='int'), max_connections=dict(type='int'), max_replication_lag=dict(type='int'), use_ssl=dict(type='bool'), max_latency_ms=dict(type='int'), comment=dict(default='', type='str'), state=dict(default='present', choices=['present', 'absent']), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool') ), supports_check_mode=True ) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, cursor_class='DictCursor') except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e) ) proxysql_server = ProxySQLServer(module) result = {} result['state'] = proxysql_server.state if proxysql_server.hostname: result['hostname'] = proxysql_server.hostname if proxysql_server.state == "present": try: if not proxysql_server.check_server_config(cursor): if not proxysql_server.check_server_config_exists(cursor): proxysql_server.create_server(module.check_mode, result, cursor) else: proxysql_server.update_server(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The server already exists in mysql_hosts" + " and doesn't need to be updated.") result['server'] = \ proxysql_server.get_server_config(cursor) except mysql_driver.Error as e: module.fail_json( msg="unable to modify server.. %s" % to_native(e) ) elif proxysql_server.state == "absent": try: if proxysql_server.check_server_config_exists(cursor): proxysql_server.delete_server(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The server is already absent from the" + " mysql_hosts memory configuration") except mysql_driver.Error as e: module.fail_json( msg="unable to remove server.. %s" % to_native(e) ) module.exit_json(**result)
def main(): argument_spec = mysql_common_argument_spec() argument_spec.update( query=dict(type='list', elements='str', required=True), login_db=dict(type='str'), positional_args=dict(type='list'), named_args=dict(type='dict'), single_transaction=dict(type='bool', default=False), ) module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=( ('positional_args', 'named_args'), ), ) db = module.params['login_db'] connect_timeout = module.params['connect_timeout'] login_user = module.params['login_user'] login_password = module.params['login_password'] ssl_cert = module.params['client_cert'] ssl_key = module.params['client_key'] ssl_ca = module.params['ca_cert'] config_file = module.params['config_file'] query = module.params["query"] if module.params["single_transaction"]: autocommit = False else: autocommit = True # Prepare args: if module.params.get("positional_args"): arguments = module.params["positional_args"] elif module.params.get("named_args"): arguments = module.params["named_args"] else: arguments = None if mysql_driver is None: module.fail_json(msg=mysql_driver_fail_msg) # Connect to DB: try: cursor, db_connection = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, db, connect_timeout=connect_timeout, cursor_class='DictCursor', autocommit=autocommit) except Exception as e: module.fail_json(msg="unable to connect to database, check login_user and " "login_password are correct or %s has the credentials. " "Exception message: %s" % (config_file, to_native(e))) # Set defaults: changed = False max_keyword_len = len(max(DML_QUERY_KEYWORDS + DDL_QUERY_KEYWORDS, key=len)) # Execute query: query_result = [] executed_queries = [] rowcount = [] for q in query: try: cursor.execute(q, arguments) except Exception as e: if not autocommit: db_connection.rollback() cursor.close() module.fail_json(msg="Cannot execute SQL '%s' args [%s]: %s" % (q, arguments, to_native(e))) try: query_result.append([dict(row) for row in cursor.fetchall()]) except Exception as e: if not autocommit: db_connection.rollback() module.fail_json(msg="Cannot fetch rows from cursor: %s" % to_native(e)) # Check DML or DDL keywords in query and set changed accordingly: q = q.lstrip()[0:max_keyword_len].upper() for keyword in DML_QUERY_KEYWORDS: if keyword in q and cursor.rowcount > 0: changed = True for keyword in DDL_QUERY_KEYWORDS: if keyword in q: changed = True executed_queries.append(cursor._last_executed) rowcount.append(cursor.rowcount) # When the module run with the single_transaction == True: if not autocommit: db_connection.commit() # Create dict with returned values: kw = { 'changed': changed, 'executed_queries': executed_queries, 'query_result': query_result, 'rowcount': rowcount, } # Exit: module.exit_json(**kw)
def main(): module = AnsibleModule(argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default="", type='path'), rule_id=dict(type='int'), active=dict(type='bool'), username=dict(type='str'), schemaname=dict(type='str'), flagIN=dict(type='int'), client_addr=dict(type='str'), proxy_addr=dict(type='str'), proxy_port=dict(type='int'), digest=dict(type='str'), match_digest=dict(type='str'), match_pattern=dict(type='str'), negate_match_pattern=dict(type='bool'), flagOUT=dict(type='int'), replace_pattern=dict(type='str'), destination_hostgroup=dict(type='int'), cache_ttl=dict(type='int'), timeout=dict(type='int'), retries=dict(type='int'), delay=dict(type='int'), mirror_flagOUT=dict(type='int'), mirror_hostgroup=dict(type='int'), error_msg=dict(type='str'), log=dict(type='bool'), apply=dict(type='bool'), comment=dict(type='str'), state=dict(default='present', choices=['present', 'absent']), force_delete=dict(default=False, type='bool'), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool')), supports_check_mode=True) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, cursor_class='DictCursor') except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)) proxysql_query_rule = ProxyQueryRule(module) result = {} result['state'] = proxysql_query_rule.state if proxysql_query_rule.state == "present": try: if not proxysql_query_rule.check_rule_cfg_exists(cursor): if proxysql_query_rule.config_data["rule_id"] and \ proxysql_query_rule.check_rule_pk_exists(cursor): proxysql_query_rule.update_rule(module.check_mode, result, cursor) else: proxysql_query_rule.create_rule(module.check_mode, result, cursor) else: result['changed'] = False result['msg'] = ("The rule already exists in" + " mysql_query_rules and doesn't need to be" + " updated.") result['rules'] = \ proxysql_query_rule.get_rule_config(cursor) except mysql_driver.Error as e: module.fail_json(msg="unable to modify rule.. %s" % to_native(e)) elif proxysql_query_rule.state == "absent": try: existing_rules = proxysql_query_rule.check_rule_cfg_exists(cursor) if existing_rules > 0: if existing_rules == 1 or \ proxysql_query_rule.force_delete: proxysql_query_rule.delete_rule(module.check_mode, result, cursor) else: module.fail_json( msg=("Operation would delete multiple rules" + " use force_delete to override this")) else: result['changed'] = False result['msg'] = ("The rule is already absent from the" + " mysql_query_rules memory configuration") except mysql_driver.Error as e: module.fail_json(msg="unable to remove rule.. %s" % to_native(e)) module.exit_json(**result)
def main(): module = AnsibleModule(argument_spec=dict( login_user=dict(default=None, type='str'), login_password=dict(default=None, no_log=True, type='str'), login_host=dict(default="127.0.0.1"), login_unix_socket=dict(default=None), login_port=dict(default=6032, type='int'), config_file=dict(default="", type='path'), variable=dict(required=True, type='str'), value=dict(), save_to_disk=dict(default=True, type='bool'), load_to_runtime=dict(default=True, type='bool')), supports_check_mode=True) perform_checks(module) login_user = module.params["login_user"] login_password = module.params["login_password"] config_file = module.params["config_file"] variable = module.params["variable"] value = module.params["value"] save_to_disk = module.params["save_to_disk"] load_to_runtime = module.params["load_to_runtime"] cursor = None try: cursor, db_conn = mysql_connect(module, login_user, login_password, config_file, cursor_class='DictCursor') except mysql_driver.Error as e: module.fail_json( msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)) result = {} if not value: try: if get_config(variable, cursor): result['changed'] = False result['msg'] = \ "Returned the variable and it's current value" result['var'] = get_config(variable, cursor) else: module.fail_json(msg="The variable \"%s\" was not found" % variable) except mysql_driver.Error as e: module.fail_json(msg="unable to get config.. %s" % to_native(e)) else: try: if get_config(variable, cursor): if not check_config(variable, value, cursor): if not module.check_mode: result['changed'] = set_config(variable, value, cursor) result['msg'] = \ "Set the variable to the supplied value" result['var'] = get_config(variable, cursor) manage_config(variable, save_to_disk, load_to_runtime, cursor, result['changed']) else: result['changed'] = True result['msg'] = ("Variable would have been set to" + " the supplied value, however" + " check_mode is enabled.") else: result['changed'] = False result['msg'] = ("The variable is already been set to" + " the supplied value") result['var'] = get_config(variable, cursor) else: module.fail_json(msg="The variable \"%s\" was not found" % variable) except mysql_driver.Error as e: module.fail_json(msg="unable to set config.. %s" % to_native(e)) module.exit_json(**result)