Exemple #1
0
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():
    argument_spec = mysql_common_argument_spec()
    argument_spec.update(
        login_db=dict(type='str'),
        filter=dict(type='list'),
        exclude_fields=dict(type='list'),
    )

    # The module doesn't support check_mode
    # because of it doesn't change anything
    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']

    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)

    cursor = mysql_connect(module,
                           login_user,
                           login_password,
                           config_file,
                           ssl_cert,
                           ssl_key,
                           ssl_ca,
                           db,
                           connect_timeout=connect_timeout,
                           cursor_class='DictCursor')

    ###############################
    # Create object and do main job

    mysql = MySQL_Info(module, cursor)

    module.exit_json(changed=False, **mysql.get_info(filter_, exclude_fields))
Exemple #3
0
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',
                                 'PROXYSQL SERVERS'
                                 '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 = 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'),
            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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 MySQLdb.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 MySQLdb.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'),
        hostname=dict(required=True, type='str'),
        port=dict(default=6032, type='int'),
        weight=dict(default=0, 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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 proxysql_servers" +
                    " and doesn't need to be updated.")
                result['server'] = \
                    proxysql_server.get_server_config(cursor)
        except MySQLdb.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" +
                                 " proxysql_servers memory configuration")
        except MySQLdb.Error as e:
            module.fail_json(msg="unable to remove server.. %s" % to_native(e))

    module.exit_json(**result)
Exemple #6
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            login_user=dict(default=None),
            login_password=dict(default=None, no_log=True),
            login_host=dict(default="localhost"),
            login_port=dict(default=3306, type='int'),
            login_unix_socket=dict(default=None),
            variable=dict(default=None),
            value=dict(default=None),
            ssl_cert=dict(default=None),
            ssl_key=dict(default=None),
            ssl_ca=dict(default=None),
            connect_timeout=dict(default=30, type='int'),
            config_file=dict(default="~/.my.cnf", type="path")
        )
    )
    user = module.params["login_user"]
    password = module.params["login_password"]
    ssl_cert = module.params["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    connect_timeout = module.params['connect_timeout']
    config_file = module.params['config_file']
    db = 'mysql'

    mysqlvar = module.params["variable"]
    value = module.params["value"]
    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 not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")
    else:
        warnings.filterwarnings('error', category=MySQLdb.Warning)

    try:
        cursor = 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 = 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)
    else:
        # Type values before using them
        value_wanted = typedvalue(value)
        value_actual = typedvalue(mysqlvar_val)
        if value_wanted == value_actual:
            module.exit_json(msg="Variable already set to requested value", changed=False)
        try:
            result = setvariable(cursor, mysqlvar, value_wanted)
        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)
        else:
            module.fail_json(msg=result, changed=False)
Exemple #7
0
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", "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"),
    ))
    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"]

    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 = 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:
            chm.append("MASTER_HOST='%s'" % master_host)
        if master_user:
            chm.append("MASTER_USER='******'" % master_user)
        if master_password:
            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:
            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:
            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:
            chm.append("MASTER_SSL_CA='%s'" % master_ssl_ca)
        if master_ssl_capath:
            chm.append("MASTER_SSL_CAPATH='%s'" % master_ssl_capath)
        if master_ssl_cert:
            chm.append("MASTER_SSL_CERT='%s'" % master_ssl_cert)
        if master_ssl_key:
            chm.append("MASTER_SSL_KEY='%s'" % master_ssl_key)
        if master_ssl_cipher:
            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(cursor, connection_name, channel)
        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(cursor, connection_name, channel)
        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 "resetslave":
        reset = reset_slave(cursor, connection_name, channel)
        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(cursor, connection_name, channel)
        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")
Exemple #8
0
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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 not 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 MySQLdb.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 MySQLdb.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'),
            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 = 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(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='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(default=None),
            login_password=dict(default=None, no_log=True),
            login_host=dict(default="localhost"),
            login_port=dict(default=3306, type='int'),
            login_unix_socket=dict(default=None),
            variable=dict(default=None),
            value=dict(default=None),
            ssl_cert=dict(default=None),
            ssl_key=dict(default=None),
            ssl_ca=dict(default=None),
            connect_timeout=dict(default=30, type='int'),
            config_file=dict(default="~/.my.cnf", type="path")
        )
    )
    user = module.params["login_user"]
    password = module.params["login_password"]
    ssl_cert = module.params["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    connect_timeout = module.params['connect_timeout']
    config_file = module.params['config_file']
    db = 'mysql'

    mysqlvar = module.params["variable"]
    value = module.params["value"]
    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 not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")
    else:
        warnings.filterwarnings('error', category=MySQLdb.Warning)

    try:
        cursor = 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 = 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)
    else:
        # Type values before using them
        value_wanted = typedvalue(value)
        value_actual = typedvalue(mysqlvar_val)
        if value_wanted == value_actual:
            module.exit_json(msg="Variable already set to requested value", changed=False)
        try:
            result = setvariable(cursor, mysqlvar, value_wanted)
        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)
        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'),
            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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 MySQLdb.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 MySQLdb.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(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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 MySQLdb.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 MySQLdb.Error as e:
            module.fail_json(
                msg="unable to set 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'),
            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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 MySQLdb.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 MySQLdb.Error as e:
            module.fail_json(
                msg="unable to remove server.. %s" % to_native(e)
            )

    module.exit_json(**result)
Exemple #15
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            login_user=dict(default=None),
            login_password=dict(default=None, no_log=True),
            login_host=dict(default="localhost"),
            login_port=dict(default=3306, type='int'),
            login_unix_socket=dict(default=None),
            user=dict(required=True, aliases=['name']),
            password=dict(default=None, no_log=True, type='str'),
            encrypted=dict(default=False, type='bool'),
            host=dict(default="localhost"),
            host_all=dict(type="bool", default="no"),
            state=dict(default="present", choices=["absent", "present"]),
            priv=dict(default=None),
            append_privs=dict(default=False, type='bool'),
            check_implicit_admin=dict(default=False, type='bool'),
            update_password=dict(default="always", choices=["always", "on_create"]),
            connect_timeout=dict(default=30, type='int'),
            config_file=dict(default="~/.my.cnf", type='path'),
            sql_log_bin=dict(default=True, type='bool'),
            ssl_cert=dict(default=None, type='path'),
            ssl_key=dict(default=None, type='path'),
            ssl_ca=dict(default=None, type='path'),
        ),
        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["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    db = 'mysql'
    sql_log_bin = module.params["sql_log_bin"]

    if not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")

    cursor = None
    try:
        if check_implicit_admin:
            try:
                cursor = mysql_connect(module, 'root', '', config_file, ssl_cert, ssl_key, ssl_ca, db,
                                       connect_timeout=connect_timeout)
            except:
                pass

        if not cursor:
            cursor = 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), exception=traceback.format_exc())
        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 = user_mod(cursor, user, host, host_all, password, encrypted, priv, append_privs, module)
                else:
                    changed = user_mod(cursor, user, host, host_all, None, encrypted, priv, append_privs, module)

            except (SQLParseError, InvalidPrivsError, MySQLdb.Error) as e:
                module.fail_json(msg=to_native(e), exception=traceback.format_exc())
        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, priv, module.check_mode)
            except (SQLParseError, InvalidPrivsError, MySQLdb.Error) as e:
                module.fail_json(msg=to_native(e), exception=traceback.format_exc())
    elif state == "absent":
        if user_exists(cursor, user, host, host_all):
            changed = user_delete(cursor, user, host, host_all, module.check_mode)
        else:
            changed = False
    module.exit_json(changed=changed, user=user)
Exemple #16
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            login_user=dict(default=None),
            login_password=dict(default=None, no_log=True),
            login_host=dict(default="localhost"),
            login_port=dict(default=3306, type='int'),
            login_unix_socket=dict(default=None),
            mode=dict(default="getslave", choices=["getmaster", "getslave", "changemaster", "stopslave", "startslave", "resetslave", "resetslaveall"]),
            master_auto_position=dict(default=False, type='bool'),
            master_host=dict(default=None),
            master_user=dict(default=None),
            master_password=dict(default=None, no_log=True),
            master_port=dict(default=None, type='int'),
            master_connect_retry=dict(default=None, type='int'),
            master_log_file=dict(default=None),
            master_log_pos=dict(default=None, type='int'),
            relay_log_file=dict(default=None),
            relay_log_pos=dict(default=None, type='int'),
            master_ssl=dict(default=False, type='bool'),
            master_ssl_ca=dict(default=None),
            master_ssl_capath=dict(default=None),
            master_ssl_cert=dict(default=None),
            master_ssl_key=dict(default=None),
            master_ssl_cipher=dict(default=None),
            connect_timeout=dict(default=30, type='int'),
            config_file=dict(default="~/.my.cnf", type='path'),
            ssl_cert=dict(default=None),
            ssl_key=dict(default=None),
            ssl_ca=dict(default=None),
        )
    )
    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["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    connect_timeout = module.params['connect_timeout']
    config_file = module.params['config_file']

    if not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")
    else:
        warnings.filterwarnings('error', category=MySQLdb.Warning)

    login_password = module.params["login_password"]
    login_user = module.params["login_user"]

    try:
        cursor = mysql_connect(module, login_user, login_password, config_file, ssl_cert, ssl_key, ssl_ca, None, 'MySQLdb.cursors.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(**status)

    elif mode in "getslave":
        status = get_slave_status(cursor)
        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(**status)

    elif mode in "changemaster":
        chm = []
        chm_params = {}
        result = {}
        if master_host:
            chm.append("MASTER_HOST=%(master_host)s")
            chm_params['master_host'] = master_host
        if master_user:
            chm.append("MASTER_USER=%(master_user)s")
            chm_params['master_user'] = master_user
        if master_password:
            chm.append("MASTER_PASSWORD=%(master_password)s")
            chm_params['master_password'] = master_password
        if master_port is not None:
            chm.append("MASTER_PORT=%(master_port)s")
            chm_params['master_port'] = master_port
        if master_connect_retry is not None:
            chm.append("MASTER_CONNECT_RETRY=%(master_connect_retry)s")
            chm_params['master_connect_retry'] = master_connect_retry
        if master_log_file:
            chm.append("MASTER_LOG_FILE=%(master_log_file)s")
            chm_params['master_log_file'] = master_log_file
        if master_log_pos is not None:
            chm.append("MASTER_LOG_POS=%(master_log_pos)s")
            chm_params['master_log_pos'] = master_log_pos
        if relay_log_file:
            chm.append("RELAY_LOG_FILE=%(relay_log_file)s")
            chm_params['relay_log_file'] = relay_log_file
        if relay_log_pos is not None:
            chm.append("RELAY_LOG_POS=%(relay_log_pos)s")
            chm_params['relay_log_pos'] = relay_log_pos
        if master_ssl:
            chm.append("MASTER_SSL=1")
        if master_ssl_ca:
            chm.append("MASTER_SSL_CA=%(master_ssl_ca)s")
            chm_params['master_ssl_ca'] = master_ssl_ca
        if master_ssl_capath:
            chm.append("MASTER_SSL_CAPATH=%(master_ssl_capath)s")
            chm_params['master_ssl_capath'] = master_ssl_capath
        if master_ssl_cert:
            chm.append("MASTER_SSL_CERT=%(master_ssl_cert)s")
            chm_params['master_ssl_cert'] = master_ssl_cert
        if master_ssl_key:
            chm.append("MASTER_SSL_KEY=%(master_ssl_key)s")
            chm_params['master_ssl_key'] = master_ssl_key
        if master_ssl_cipher:
            chm.append("MASTER_SSL_CIPHER=%(master_ssl_cipher)s")
            chm_params['master_ssl_cipher'] = master_ssl_cipher
        if master_auto_position:
            chm.append("MASTER_AUTO_POSITION = 1")
        try:
            changemaster(cursor, chm, chm_params)
        except MySQLdb.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(**result)
    elif mode in "startslave":
        started = start_slave(cursor)
        if started is True:
            module.exit_json(msg="Slave started ", changed=True)
        else:
            module.exit_json(msg="Slave already started (Or cannot be started)", changed=False)
    elif mode in "stopslave":
        stopped = stop_slave(cursor)
        if stopped is True:
            module.exit_json(msg="Slave stopped", changed=True)
        else:
            module.exit_json(msg="Slave already stopped", changed=False)
    elif mode in "resetslave":
        reset = reset_slave(cursor)
        if reset is True:
            module.exit_json(msg="Slave reset", changed=True)
        else:
            module.exit_json(msg="Slave already reset", changed=False)
    elif mode in "resetslaveall":
        reset = reset_slave_all(cursor)
        if reset is True:
            module.exit_json(msg="Slave reset", changed=True)
        else:
            module.exit_json(msg="Slave already reset", 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'),
            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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 MySQLdb.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 MySQLdb.Error as e:
            module.fail_json(
                msg="unable to remove rule.. %s" % to_native(e)
            )

    module.exit_json(**result)
Exemple #18
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            login_user=dict(default=None),
            login_password=dict(default=None, no_log=True),
            login_host=dict(default="localhost"),
            login_port=dict(default=3306, type='int'),
            login_unix_socket=dict(default=None),
            name=dict(required=True, aliases=['db']),
            encoding=dict(default=""),
            collation=dict(default=""),
            target=dict(default=None, type='path'),
            state=dict(default="present", choices=["absent", "present", "dump", "import"]),
            ssl_cert=dict(default=None, type='path'),
            ssl_key=dict(default=None, type='path'),
            ssl_ca=dict(default=None, type='path'),
            connect_timeout=dict(default=30, type='int'),
            config_file=dict(default="~/.my.cnf", type='path'),
            single_transaction=dict(default=False, type='bool'),
            quick=dict(default=True, type='bool'),
        ),
        supports_check_mode=True
    )

    if not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")

    db = module.params["name"]
    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["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    connect_timeout = module.params['connect_timeout']
    config_file = module.params['config_file']
    login_password = module.params["login_password"]
    login_user = module.params["login_user"]
    login_host = module.params["login_host"]
    single_transaction = module.params["single_transaction"]
    quick = module.params["quick"]

    if state in ['dump', 'import']:
        if target is None:
            module.fail_json(msg="with state=%s target is required" % state)
        if db == 'all':
            db = 'mysql'
            all_databases = True
        else:
            all_databases = False
    else:
        if db == 'all':
            module.fail_json(msg="name is not allowed to equal 'all' unless state equals import, or dump.")
    try:
        cursor = 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
    if db_exists(cursor, db):
        if state == "absent":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                try:
                    changed = db_delete(cursor, db)
                except Exception as e:
                    module.fail_json(msg="error deleting database: %s" % to_native(e))
                module.exit_json(changed=changed, db=db)

        elif state == "dump":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                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)
                if rc != 0:
                    module.fail_json(msg="%s" % stderr)
                else:
                    module.exit_json(changed=True, db=db, msg=stdout)

        elif state == "import":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                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)
                if rc != 0:
                    module.fail_json(msg="%s" % stderr)
                else:
                    module.exit_json(changed=True, db=db, msg=stdout)

        elif state == "present":
            if module.check_mode:
                module.exit_json(changed=False, db=db)
            module.exit_json(changed=False, db=db)

    else:
        if state == "present":
            if module.check_mode:
                changed = True
            else:
                try:
                    changed = db_create(cursor, db, 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)

        elif state == "import":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                try:
                    changed = db_create(cursor, db, encoding, collation)
                    if changed:
                        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)
                        if rc != 0:
                            module.fail_json(msg="%s" % stderr)
                        else:
                            module.exit_json(changed=True, db=db, msg=stdout)
                except Exception as e:
                    module.fail_json(msg="error creating database: %s" % to_native(e),
                                     exception=traceback.format_exc())

        elif state == "absent":
            if module.check_mode:
                module.exit_json(changed=False, db=db)
            module.exit_json(changed=False, db=db)

        elif state == "dump":
            if module.check_mode:
                module.exit_json(changed=False, db=db)
            module.fail_json(msg="Cannot dump database %s - not found" % (db))
Exemple #19
0
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'),
        ),
        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"]
    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"]

    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 = 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)
    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)
    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)
        if rc != 0:
            module.fail_json(msg="%s" % stderr)
        module.exit_json(changed=True, db=db_name, db_list=db, msg=stdout)
    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)
        if rc != 0:
            module.fail_json(msg="%s" % stderr)
        module.exit_json(changed=True, db=db_name, db_list=db, msg=stdout)
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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file)
    except MySQLdb.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 MySQLdb.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(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 = 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)
Exemple #22
0
def main():
    module = AnsibleModule(argument_spec=dict(
        login_user=dict(default=None),
        login_password=dict(default=None, no_log=True),
        login_host=dict(default="localhost"),
        login_port=dict(default=3306, type='int'),
        login_unix_socket=dict(default=None),
        name=dict(required=True, aliases=['db']),
        encoding=dict(default=""),
        collation=dict(default=""),
        target=dict(default=None, type='path'),
        state=dict(default="present",
                   choices=["absent", "present", "dump", "import"]),
        ssl_cert=dict(default=None, type='path'),
        ssl_key=dict(default=None, type='path'),
        ssl_ca=dict(default=None, type='path'),
        connect_timeout=dict(default=30, type='int'),
        config_file=dict(default="~/.my.cnf", type='path'),
        no_data=dict(default=False, type='bool'),
        single_transaction=dict(default=False, type='bool'),
        quick=dict(default=True, type='bool'),
        ignore_tables=dict(default=[], type='list')),
                           supports_check_mode=True)

    if not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")

    db = module.params["name"]
    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["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    connect_timeout = module.params['connect_timeout']
    config_file = module.params['config_file']
    login_password = module.params["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"]

    if state in ['dump', 'import']:
        if target is None:
            module.fail_json(msg="with state=%s target is required" % state)
        if db == 'all':
            db = 'mysql'
            all_databases = True
        else:
            all_databases = False
    else:
        if db == 'all':
            module.fail_json(
                msg=
                "name is not allowed to equal 'all' unless state equals import, or dump."
            )
    try:
        cursor = 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
    if db_exists(cursor, db):
        if state == "absent":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                try:
                    changed = db_delete(cursor, db)
                except Exception as e:
                    module.fail_json(msg="error deleting database: %s" %
                                     to_native(e))
                module.exit_json(changed=changed, db=db)

        elif state == "dump":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                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)
                if rc != 0:
                    module.fail_json(msg="%s" % stderr)
                else:
                    module.exit_json(changed=True, db=db, msg=stdout)

        elif state == "import":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                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)
                if rc != 0:
                    module.fail_json(msg="%s" % stderr)
                else:
                    module.exit_json(changed=True, db=db, msg=stdout)

        elif state == "present":
            if module.check_mode:
                module.exit_json(changed=False, db=db)
            module.exit_json(changed=False, db=db)

    else:
        if state == "present":
            if module.check_mode:
                changed = True
            else:
                try:
                    changed = db_create(cursor, db, 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)

        elif state == "import":
            if module.check_mode:
                module.exit_json(changed=True, db=db)
            else:
                try:
                    changed = db_create(cursor, db, encoding, collation)
                    if changed:
                        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)
                        if rc != 0:
                            module.fail_json(msg="%s" % stderr)
                        else:
                            module.exit_json(changed=True, db=db, msg=stdout)
                except Exception as e:
                    module.fail_json(msg="error creating database: %s" %
                                     to_native(e),
                                     exception=traceback.format_exc())

        elif state == "absent":
            if module.check_mode:
                module.exit_json(changed=False, db=db)
            module.exit_json(changed=False, db=db)

        elif state == "dump":
            if module.check_mode:
                module.exit_json(changed=False, db=db)
            module.fail_json(msg="Cannot dump database %s - not found" % (db))
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', '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']),
    ))
    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']

    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 = 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(**status)

    elif mode in "getslave":
        status = get_slave_status(cursor)
        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(**status)

    elif mode in "changemaster":
        chm = []
        chm_params = {}
        result = {}
        if master_host:
            chm.append("MASTER_HOST=%(master_host)s")
            chm_params['master_host'] = master_host
        if master_user:
            chm.append("MASTER_USER=%(master_user)s")
            chm_params['master_user'] = master_user
        if master_password:
            chm.append("MASTER_PASSWORD=%(master_password)s")
            chm_params['master_password'] = master_password
        if master_port is not None:
            chm.append("MASTER_PORT=%(master_port)s")
            chm_params['master_port'] = master_port
        if master_connect_retry is not None:
            chm.append("MASTER_CONNECT_RETRY=%(master_connect_retry)s")
            chm_params['master_connect_retry'] = master_connect_retry
        if master_log_file:
            chm.append("MASTER_LOG_FILE=%(master_log_file)s")
            chm_params['master_log_file'] = master_log_file
        if master_log_pos is not None:
            chm.append("MASTER_LOG_POS=%(master_log_pos)s")
            chm_params['master_log_pos'] = master_log_pos
        if relay_log_file:
            chm.append("RELAY_LOG_FILE=%(relay_log_file)s")
            chm_params['relay_log_file'] = relay_log_file
        if relay_log_pos is not None:
            chm.append("RELAY_LOG_POS=%(relay_log_pos)s")
            chm_params['relay_log_pos'] = relay_log_pos
        if master_ssl:
            chm.append("MASTER_SSL=1")
        if master_ssl_ca:
            chm.append("MASTER_SSL_CA=%(master_ssl_ca)s")
            chm_params['master_ssl_ca'] = master_ssl_ca
        if master_ssl_capath:
            chm.append("MASTER_SSL_CAPATH=%(master_ssl_capath)s")
            chm_params['master_ssl_capath'] = master_ssl_capath
        if master_ssl_cert:
            chm.append("MASTER_SSL_CERT=%(master_ssl_cert)s")
            chm_params['master_ssl_cert'] = master_ssl_cert
        if master_ssl_key:
            chm.append("MASTER_SSL_KEY=%(master_ssl_key)s")
            chm_params['master_ssl_key'] = master_ssl_key
        if master_ssl_cipher:
            chm.append("MASTER_SSL_CIPHER=%(master_ssl_cipher)s")
            chm_params['master_ssl_cipher'] = master_ssl_cipher
        if master_auto_position:
            chm.append("MASTER_AUTO_POSITION = 1")
        try:
            changemaster(cursor, chm, chm_params)
        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(**result)
    elif mode in "startslave":
        started = start_slave(cursor)
        if started is True:
            module.exit_json(msg="Slave started ", changed=True)
        else:
            module.exit_json(
                msg="Slave already started (Or cannot be started)",
                changed=False)
    elif mode in "stopslave":
        stopped = stop_slave(cursor)
        if stopped is True:
            module.exit_json(msg="Slave stopped", changed=True)
        else:
            module.exit_json(msg="Slave already stopped", changed=False)
    elif mode in "resetslave":
        reset = reset_slave(cursor)
        if reset is True:
            module.exit_json(msg="Slave reset", changed=True)
        else:
            module.exit_json(msg="Slave already reset", changed=False)
    elif mode in "resetslaveall":
        reset = reset_slave_all(cursor)
        if reset is True:
            module.exit_json(msg="Slave reset", changed=True)
        else:
            module.exit_json(msg="Slave already reset", changed=False)

    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'),
            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 = mysql_connect(module,
                               login_user,
                               login_password,
                               config_file,
                               cursor_class=MySQLdb.cursors.DictCursor)
    except MySQLdb.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 MySQLdb.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 MySQLdb.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(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 = 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)
        )

    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)
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 = 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)
Exemple #27
0
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='str'),
            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']),
            connect_timeout=dict(type='int', default=30),
            config_file=dict(type='path', default='~/.my.cnf'),
            sql_log_bin=dict(type='bool', default=True),
            ssl_cert=dict(type='path'),
            ssl_key=dict(type='path'),
            ssl_ca=dict(type='path'),
        ),
        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["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    db = 'mysql'
    sql_log_bin = module.params["sql_log_bin"]

    if mysql_driver is None:
        module.fail_json(msg=mysql_driver_fail_msg)

    cursor = None
    try:
        if check_implicit_admin:
            try:
                cursor = mysql_connect(module, 'root', '', config_file, ssl_cert, ssl_key, ssl_ca, db,
                                       connect_timeout=connect_timeout)
            except Exception:
                pass

        if not cursor:
            cursor = 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 = user_mod(cursor, user, host, host_all, password, encrypted, priv, append_privs, module)
                else:
                    changed = user_mod(cursor, user, host, host_all, None, encrypted, 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, priv, module.check_mode)
            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)
        else:
            changed = False
    module.exit_json(changed=changed, user=user)
def main():
    module = AnsibleModule(argument_spec=dict(
        status=dict(default=None, type='list', required=True),
        login_user=dict(default=None),
        login_password=dict(default=None, no_log=True),
        login_host=dict(default="localhost"),
        login_port=dict(default=3306, type='int'),
        login_unix_socket=dict(default=None),
        ssl_cert=dict(default=None),
        ssl_key=dict(default=None),
        ssl_ca=dict(default=None),
        connect_timeout=dict(default=30, type='int'),
        config_file=dict(default="~/.my.cnf", type="path")))
    user = module.params["login_user"]
    password = module.params["login_password"]
    ssl_cert = module.params["ssl_cert"]
    ssl_key = module.params["ssl_key"]
    ssl_ca = module.params["ssl_ca"]
    connect_timeout = module.params['connect_timeout']
    config_file = module.params['config_file']
    db = 'mysql'

    mysqlstatus = module.params["status"]
    if not mysqldb_found:
        module.fail_json(msg="The MySQL-python module is required.")
    else:
        warnings.filterwarnings('error', category=MySQLdb.Warning)

    try:
        cursor = mysql_connect(
            module,
            user,
            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)))

    statuses = {}
    for status in mysqlstatus:
        if match('^[0-9a-z_\%]+$', status) is None:
            module.fail_json(msg="invalid status name \"%s\"" % status)
        mysqlstatus_res = getstatus(cursor, status)
        if mysqlstatus_res is None:
            statuses[status] = None
        else:
            mysqlstatus_res = [(x[0].lower(), typedvalue(x[1]))
                               for x in mysqlstatus_res]
            for res in mysqlstatus_res:
                statuses[res[0]] = res[1]

    module.exit_json(msg="Status found", status=statuses, changed=False)