Exemplo n.º 1
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        filter=dict(type='list', elements='str', required=False))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    ssl = module.params['ssl']
    filter_ = module.params['filter']

    if filter_:
        filter_ = [f.strip() for f in filter_]

    connection_params = {
        'host': login_host,
        'port': login_port,
    }

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    client = MongoClient(**connection_params)

    if login_user:
        try:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)
        except Exception as e:
            module.fail_json(msg='Unable to authenticate: %s' % to_native(e))

    # Get server version:
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(e))

    # Get driver version::
    driver_version = LooseVersion(PyMongoVersion)

    # Check driver and server version compatibility:
    check_compatibility(module, srv_version, driver_version)

    # Initialize an object and start main work:
    mongodb = MongoDbInfo(module, client)

    module.exit_json(changed=False, **mongodb.get_info(filter_))
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(database=dict(required=True, aliases=['db']),
                         name=dict(required=True, aliases=['user']),
                         password=dict(aliases=['pass'], no_log=True),
                         replica_set=dict(default=None),
                         roles=dict(default=None, type='list', elements='raw'),
                         state=dict(default='present',
                                    choices=['absent', 'present']),
                         update_password=dict(default="always",
                                              choices=["always", "on_create"]))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )
    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    login_database = module.params['login_database']

    replica_set = module.params['replica_set']
    db_name = module.params['database']
    user = module.params['name']
    password = module.params['password']
    ssl = module.params['ssl']
    roles = module.params['roles'] or []
    state = module.params['state']
    update_password = module.params['update_password']

    try:
        connection_params = {
            "host": login_host,
            "port": int(login_port),
        }

        if replica_set:
            connection_params["replicaset"] = replica_set

        if ssl:
            connection_params = ssl_connection_options(connection_params,
                                                       module)

        client = MongoClient(**connection_params)

        if login_user is None and login_password is None:
            mongocnf_creds = load_mongocnf()
            if mongocnf_creds is not False:
                login_user = mongocnf_creds['user']
                login_password = mongocnf_creds['password']
        elif login_password is None or login_user is None:
            module.fail_json(
                msg=
                'when supplying login arguments, both login_user and login_password must be provided'
            )

        if login_user is not None and login_password is not None:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)
            # Get server version:
            try:
                srv_version = LooseVersion(client.server_info()['version'])
            except Exception as e:
                module.fail_json(
                    msg='Unable to get MongoDB server version: %s' %
                    to_native(e))

            # Get driver version::
            driver_version = LooseVersion(PyMongoVersion)

            # Check driver and server version compatibility:
            check_compatibility(module, srv_version, driver_version)
        elif LooseVersion(PyMongoVersion) >= LooseVersion('3.0'):
            if db_name != "admin":
                module.fail_json(
                    msg=
                    'The localhost login exception only allows the first admin account to be created'
                )
            # else: this has to be the first admin user added

    except Exception as e:
        module.fail_json(msg='unable to connect to database: %s' %
                         to_native(e),
                         exception=traceback.format_exc())

    if state == 'present':
        if password is None and update_password == 'always':
            module.fail_json(
                msg=
                'password parameter required when adding a user unless update_password is set to on_create'
            )

        try:
            if update_password != 'always':
                uinfo = user_find(client, user, db_name)
                if uinfo:
                    password = None
                    if not check_if_roles_changed(uinfo, roles, db_name):
                        module.exit_json(changed=False, user=user)

            if module.check_mode:
                module.exit_json(changed=True, user=user)

            user_add(module, client, db_name, user, password, roles)
        except Exception as e:
            module.fail_json(msg='Unable to add or update user: %s' %
                             to_native(e),
                             exception=traceback.format_exc())
        finally:
            try:
                client.close()
            except Exception:
                pass
            # Here we can  check password change if mongo provide a query for that : https://jira.mongodb.org/browse/SERVER-22848
            # newuinfo = user_find(client, user, db_name)
            # if uinfo['role'] == newuinfo['role'] and CheckPasswordHere:
            #    module.exit_json(changed=False, user=user)

    elif state == 'absent':
        try:
            user_remove(module, client, db_name, user)
        except Exception as e:
            module.fail_json(msg='Unable to remove user: %s' % to_native(e),
                             exception=traceback.format_exc())
        finally:
            try:
                client.close()
            except Exception:
                pass
    module.exit_json(changed=True, user=user)
Exemplo n.º 3
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        option_name=dict(type='<DATA TYPE>', default='<VALUE>'))

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    option_name = module.params['option_name']

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)
    try:
        client = MongoClient(**connection_params)
    except Exception as e:
        module.fail_json(msg='Unable to connect to database: %s' %
                         to_native(e))

    try:
        # If we have auth details use then otherwise attempt without
        if login_user is None and login_password is None:
            mongocnf_creds = load_mongocnf()
            if mongocnf_creds is not False:
                login_user = mongocnf_creds['user']
                login_password = mongocnf_creds['password']
        elif login_password is None or login_user is None:
            module.fail_json(
                msg=
                "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
            )
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(e))

    if login_user is not None and login_password is not None:
        try:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)
        except Exception as excep:
            module.fail_json(msg='Unable to authenticate with MongoDB: %s' %
                             to_native(excep))
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(e))

    # Get driver version::
    driver_version = LooseVersion(PyMongoVersion)

    # Check driver and server version compatibility:
    try:
        check_compatibility(module, srv_version, driver_version)
    except Exception as e:
        module.fail_json(
            msg='Unable to validate MongoDB driver compatibility: %s' %
            to_native(e))

    # main logic of module here
    if module.check_mode:
        pass
    else:
        pass

    module.exit_json(**result)
Exemplo n.º 4
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        interval=dict(type='int', default=30),
        poll=dict(type='int', default=1),
        replica_set=dict(type='str', default="rs0"),
        validate=dict(type='str', choices=['default', 'votes', 'minimal'], default='default'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
        required_together=[['login_user', 'login_password']],
    )
    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    replica_set = module.params['replica_set']
    ssl = module.params['ssl']
    poll = module.params['poll']
    interval = module.params['interval']

    result = dict(
        failed=False,
        replica_set=replica_set,
    )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as e:
        module.fail_json(msg='Unable to connect to database: %s' % to_native(e))

    try:
        # Get server version:
        try:
            srv_version = LooseVersion(client.server_info()['version'])
        except Exception as e:
            module.fail_json(msg='Unable to get MongoDB server version: %s' % to_native(e))

        # Get driver version::
        driver_version = LooseVersion(PyMongoVersion)

        # Check driver and server version compatibility:
        check_compatibility(module, srv_version, driver_version)
    except Exception as excep:
        if excep.code != 13:
            raise excep
        if login_user is None or login_password is None:
            raise excep
        client.admin.authenticate(login_user, login_password, source=login_database)
        check_compatibility(module, client)

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(msg="When supplying login arguments, both 'login_user' and 'login_password' must be provided")

    try:
        client['admin'].command('listDatabases', 1.0)  # if this throws an error we need to authenticate
    except Exception as excep:
        if "not authorized on" in str(excep) or "command listDatabases requires authentication" in str(excep):
            if login_user is not None and login_password is not None:
                try:
                    client.admin.authenticate(login_user, login_password, source=login_database)
                except Exception as excep:
                    module.fail_json(msg='unable to connect to database: %s' % to_native(excep), exception=traceback.format_exc())
            else:
                module.fail_json(msg='unable to connect to database: %s' % to_native(excep), exception=traceback.format_exc())
        else:
            module.fail_json(msg='unable to connect to database: %s' % to_native(excep), exception=traceback.format_exc())

    if len(replica_set) == 0:
        module.fail_json(msg="Parameter 'replica_set' must not be an empty string")

    try:
        status, msg, return_doc = replicaset_status_poll(client, module)  # Sort out the return doc
        replicaset = return_doc['replicaset']
        iterations = return_doc['iterations']
    except Exception as e:
        module.fail_json(msg='Unable to query replica_set info: {0}: {1}'.format(str(e), msg))

    if status is False:
        module.fail_json(msg=msg, replicaset=replicaset, iterations=iterations)
    else:
        module.exit_json(msg=msg, replicaset=replicaset, iterations=iterations)
Exemplo n.º 5
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(autosplit=dict(type='bool', default=None),
                         chunksize=dict(type='int', default=None),
                         mongos_process=dict(type='str',
                                             required=False,
                                             default="mongos"),
                         state=dict(type='str',
                                    default="started",
                                    choices=["started", "stopped"]),
                         window=dict(type='raw', default=None))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not has_ordereddict:
        module.fail_json(
            msg=
            'Cannot import OrderedDict class. You can probably install with: pip install ordereddict'
        )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    balancer_state = module.params['state']
    autosplit = module.params['autosplit']
    chunksize = module.params['chunksize']
    mongos_process = module.params['mongos_process']
    ssl = module.params['ssl']
    window = module.params['window']

    # Validate window
    validate_window(window, module)

    result = dict(changed=False, )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as excep:
        module.fail_json(msg='Unable to connect to MongoDB: %s' %
                         to_native(excep))

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(
            msg=
            "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
        )

    try:
        try:
            client['admin'].command(
                'listDatabases',
                1.0)  # if this throws an error we need to authenticate
        except Exception as excep:
            if excep.code == 13:
                if login_user is not None and login_password is not None:
                    client.admin.authenticate(login_user,
                                              login_password,
                                              source=login_database)
                else:
                    module.fail_json(msg='No credentials to authenticate: %s' %
                                     to_native(excep))
            else:
                module.fail_json(msg='Unknown error: %s' % to_native(excep))
    except Exception as excep:
        module.fail_json(msg='unable to connect to database: %s' %
                         to_native(excep),
                         exception=traceback.format_exc())
    # Get server version:
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as excep:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(excep))
    try:
        # Get driver version::
        driver_version = LooseVersion(PyMongoVersion)
        # Check driver and server version compatibility:
        check_compatibility(module, srv_version, driver_version)
    except Exception as excep:
        module.fail_json(msg='Unable to authenticate with MongoDB: %s' %
                         to_native(excep))

    changed = False

    cluster_balancer_state = None
    cluster_autosplit = None
    cluster_chunksize = None
    old_balancer_state = None
    new_balancer_state = None
    old_autosplit = None
    new_autosplit = None
    old_chunksize = None
    new_chunksize = None

    try:

        if client["admin"].command(
                "serverStatus")["process"] != mongos_process:
            module.fail_json(
                msg="Process running on {0}:{1} is not a {2}".format(
                    login_host, login_port, mongos_process))

        cluster_balancer_state = get_balancer_state(client)
        if autosplit is not None:
            cluster_autosplit = get_autosplit(client)
        if chunksize is not None:
            cluster_chunksize = get_chunksize(client)

        if module.check_mode:
            if balancer_state != cluster_balancer_state:
                old_balancer_state = cluster_balancer_state
                new_balancer_state = balancer_state
                changed = True
            if (autosplit is not None and autosplit != cluster_autosplit):
                old_autosplit = cluster_autosplit
                new_autosplit = autosplit
                changed = True
            if (chunksize is not None and chunksize != cluster_chunksize):
                old_chunksize = cluster_chunksize
                new_chunksize = chunksize
                changed = True
            if window is not None:
                if balancing_window(client, window.get('start'),
                                    window.get('stop')):
                    if window['state'] == "present":
                        pass
                    else:
                        changed = True
                else:
                    if window['state'] == "present":
                        changed = True
                    else:
                        pass
        else:
            if balancer_state is not None \
                    and balancer_state != cluster_balancer_state:
                if balancer_state == "started":
                    start_balancer(client)
                    old_balancer_state = cluster_balancer_state
                    new_balancer_state = get_balancer_state(client)
                    changed = True
                else:
                    stop_balancer(client)
                    old_balancer_state = cluster_balancer_state
                    new_balancer_state = get_balancer_state(client)
                    changed = True
            if autosplit is not None \
                    and autosplit != cluster_autosplit:
                if autosplit:
                    enable_autosplit(client)
                    old_autosplit = cluster_autosplit
                    new_autosplit = autosplit
                    changed = True
                else:
                    disable_autosplit(client)
                    old_autosplit = cluster_autosplit
                    new_autosplit = autosplit
                    changed = True
            if (chunksize is not None and chunksize != cluster_chunksize):
                set_chunksize(client, chunksize)
                old_chunksize = cluster_chunksize
                new_chunksize = chunksize
                changed = True
            if window is not None:
                if balancing_window(client, window.get('start'),
                                    window.get('stop')):
                    if window['state'] == "present":
                        pass
                    else:
                        remove_balancing_window(client)
                        changed = True
                else:
                    if window['state'] == "present":
                        set_balancing_window(client, window['start'],
                                             window['stop'])
                        changed = True
                    else:
                        pass
    except Exception as excep:
        result["msg"] = "An error occurred: {0}".format(excep)

    result['changed'] = changed
    if old_balancer_state is not None:
        result['old_balancer_state'] = old_balancer_state
        result['new_balancer_state'] = new_balancer_state
    if old_autosplit is not None:
        result['old_autosplit'] = old_autosplit
        result['new_autosplit'] = new_autosplit
    if old_chunksize is not None:
        result['old_chunksize'] = old_chunksize
        result['new_chunksize'] = new_chunksize

    module.exit_json(**result)
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(force=dict(type='bool', default=False),
                         interval=dict(type='int', default=30),
                         poll=dict(type='int', default=1),
                         secondary_catch_up=dict(type='int', default=10),
                         stepdown_seconds=dict(type='int', default=60))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )
    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    ssl = module.params['ssl']
    poll = module.params['poll']
    interval = module.params['interval']
    stepdown_seconds = module.params['stepdown_seconds']
    secondary_catch_up = module.params['secondary_catch_up']

    result = dict(failed=False, )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as e:
        module.fail_json(msg='Unable to connect to database: %s' %
                         to_native(e))

    try:
        # Get server version:
        try:
            srv_version = LooseVersion(client.server_info()['version'])
        except Exception as e:
            module.fail_json(msg='Unable to get MongoDB server version: %s' %
                             to_native(e))

        # Get driver version::
        driver_version = LooseVersion(PyMongoVersion)

        # Check driver and server version compatibility:
        check_compatibility(module, srv_version, driver_version)
    except Exception as excep:
        if "not authorized on" not in str(
                excep) and "there are no users authenticated" not in str(
                    excep):
            raise excep
        if login_user is None or login_password is None:
            raise excep
        client.admin.authenticate(login_user,
                                  login_password,
                                  source=login_database)
        check_compatibility(module, client)

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(
            msg=
            "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
        )

    try:
        client['admin'].command(
            'listDatabases',
            1.0)  # if this throws an error we need to authenticate
    except Exception as excep:
        if "not authorized on" in str(
                excep
        ) or "command listDatabases requires authentication" in str(excep):
            if login_user is not None and login_password is not None:
                try:
                    client.admin.authenticate(login_user,
                                              login_password,
                                              source=login_database)
                except Exception as excep:
                    module.fail_json(msg='unable to connect to database: %s' %
                                     to_native(excep),
                                     exception=traceback.format_exc())
            else:
                module.fail_json(msg='unable to connect to database: %s' %
                                 to_native(excep),
                                 exception=traceback.format_exc())
        else:
            module.fail_json(msg='unable to connect to database: %s' %
                             to_native(excep),
                             exception=traceback.format_exc())

    try:
        status, msg, return_doc = member_stepdown(client, module)
        iterations = return_doc['iterations']
        changed = return_doc['changed']
    except Exception as e:
        module.fail_json(msg='Unable to query replica_set info: %s' % str(e))

    if status is False:
        module.fail_json(msg=msg, iterations=iterations, changed=changed)
    else:
        module.exit_json(msg=msg, iterations=iterations, changed=changed)
Exemplo n.º 7
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        force=dict(type='bool', default=False),
        timeout=dict(type='int', default=10)
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    try:
        from collections import OrderedDict
    except ImportError as excep:
        try:
            from ordereddict import OrderedDict
        except ImportError as excep:
            module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict: %s'
                             % to_native(excep))

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    force = module.params['force']
    timeout = module.params['timeout']
    ssl = module.params['ssl']

    result = dict(
        changed=False,
    )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as excep:
        module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep))

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(msg="When supplying login arguments, both 'login_user' and 'login_password' must be provided")

    if login_user is not None and login_password is not None:
        try:
            client.admin.authenticate(login_user, login_password, source=login_database)
            # Get server version:
            try:
                srv_version = LooseVersion(client.server_info()['version'])
            except Exception as excep:
                module.fail_json(msg='Unable to get MongoDB server version: %s' % to_native(excep))

            # Get driver version::
            driver_version = LooseVersion(PyMongoVersion)
            # Check driver and server version compatibility:
            check_compatibility(module, srv_version, driver_version)
        except Exception as excep:
            module.fail_json(msg='Unable to authenticate with MongoDB: %s' % to_native(excep))

        try:
            cmd_doc = OrderedDict([
                ('shutdown', 1),
                ('force', force),
                ('timeout', timeout)
            ])
            client['admin'].command(cmd_doc)
            result["changed"] = True
            result["msg"] = "mongod process was terminated sucessfully"
        except Exception as excep:
            if "connection closed" in str(excep):
                result["changed"] = True
                result["msg"] = "mongod process was terminated sucessfully"
            else:
                result["msg"] = "An error occurred: {0}".format(excep)

    module.exit_json(**result)
Exemplo n.º 8
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(arbiter_at_index=dict(type='int'),
                         chaining_allowed=dict(type='bool', default=True),
                         election_timeout_millis=dict(type='int',
                                                      default=10000),
                         heartbeat_timeout_secs=dict(type='int', default=10),
                         members=dict(type='list', elements='raw'),
                         protocol_version=dict(type='int',
                                               default=1,
                                               choices=[0, 1]),
                         replica_set=dict(type='str', default="rs0"),
                         validate=dict(type='bool', default=True))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    replica_set = module.params['replica_set']
    members = module.params['members']
    arbiter_at_index = module.params['arbiter_at_index']
    validate = module.params['validate']
    ssl = module.params['ssl']
    protocol_version = module.params['protocol_version']
    chaining_allowed = module.params['chaining_allowed']
    heartbeat_timeout_secs = module.params['heartbeat_timeout_secs']
    election_timeout_millis = module.params['election_timeout_millis']

    if validate:
        if len(members) <= 2 or len(members) % 2 == 0:
            module.fail_json(
                msg=
                "MongoDB Replicaset validation failed. Invalid number of replicaset members."
            )
        if arbiter_at_index is not None and len(members) - 1 < arbiter_at_index:
            module.fail_json(
                msg=
                "MongoDB Replicaset validation failed. Invalid arbiter index.")

    result = dict(
        changed=False,
        replica_set=replica_set,
    )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)

        rs = replicaset_find(client)

        # Everything after the next else will need to be changed as we're using
        # isMaster that does not require auth...
        if isinstance(rs, str):
            if replica_set == rs:
                result['changed'] = False
                result['replica_set'] = rs
                module.exit_json(**result)
            else:
                module.fail_json(
                    msg=
                    "The replica_set name of {0} does not match the expected: {1}"
                    .format(rs, replica_set))
        else:  # replicaset does not exit

            # Some validation stuff
            if len(replica_set) == 0:
                module.fail_json(
                    msg="Parameter replica_set must not be an empty string")

            if module.check_mode is False:
                try:
                    # If we have auth details use then otherwise attempt without
                    if login_user is None and login_password is None:
                        mongocnf_creds = load_mongocnf()
                        if mongocnf_creds is not False:
                            login_user = mongocnf_creds['user']
                            login_password = mongocnf_creds['password']
                    elif login_password is None or login_user is None:
                        module.fail_json(
                            msg=
                            "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
                        )

                    if login_user is not None and login_password is not None:
                        try:
                            client.admin.authenticate(login_user,
                                                      login_password,
                                                      source=login_database)
                            # Get server version:
                            try:
                                srv_version = LooseVersion(
                                    client.server_info()['version'])
                            except Exception as e:
                                module.fail_json(
                                    msg=
                                    'Unable to get MongoDB server version: %s'
                                    % to_native(e))

                            # Get driver version::
                            driver_version = LooseVersion(PyMongoVersion)
                            # Check driver and server version compatibility:
                            check_compatibility(module, srv_version,
                                                driver_version)
                        except Exception as excep:
                            module.fail_json(
                                msg='Unable to authenticate with MongoDB: %s' %
                                to_native(excep))
                    replicaset_add(module, client, replica_set, members,
                                   arbiter_at_index, protocol_version,
                                   chaining_allowed, heartbeat_timeout_secs,
                                   election_timeout_millis)
                    result['changed'] = True
                except Exception as e:
                    module.fail_json(msg='Unable to create replica_set: %s' %
                                     to_native(e))
            else:
                result['changed'] = True

            module.exit_json(**result)
    except Exception as e:
        module.fail_json(msg='Unable to connect to database: %s' %
                         to_native(e))
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        name=dict(type='str', required=True),
        namespace=dict(type='str'),
        ranges=dict(type='list', elements='list'),
        mongos_process=dict(type='str', required=False, default="mongos"),
        state=dict(type='str', default="present", choices=["present", "absent"]),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
        required_if=[("state", "present", ("namespace", "ranges"))]
    )

    if not has_ordereddict:
        module.fail_json(msg='Cannot import OrderedDict class. You can probably install with: pip install ordereddict')

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    state = module.params['state']
    zone_name = module.params['name']
    namespace = module.params['namespace']
    ranges = module.params['ranges']
    mongos_process = module.params['mongos_process']
    ssl = module.params['ssl']

    if ranges is not None:
        if not isinstance(ranges, list) or not isinstance(ranges[0], list) or not isinstance(ranges[0][0], dict):
            module.fail_json(msg="Provided ranges are invalid {0} {1} {2}".format(str(type(ranges)),
                                                                                  str(type(ranges[0])),
                                                                                  str(type(ranges[0][0]))))

    result = dict(
        changed=False,
    )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as excep:
        module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep))

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(msg="When supplying login arguments, both 'login_user' and 'login_password' must be provided")

    try:
        try:
            client['admin'].command('listDatabases', 1.0)  # if this throws an error we need to authenticate
        except Exception as excep:
            if hasattr(excep, 'code') and excep.code == 13:
                if login_user is not None and login_password is not None:
                    client.admin.authenticate(login_user, login_password, source=login_database)
                else:
                    module.fail_json(msg='No credentials to authenticate: %s' % to_native(excep))
            else:
                module.fail_json(msg='Unknown error: %s' % to_native(excep))
    except Exception as excep:
        module.fail_json(msg='unable to connect to database: %s' % to_native(excep), exception=traceback.format_exc())
    # Get server version:
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as excep:
        module.fail_json(msg='Unable to get MongoDB server version: %s' % to_native(excep))
    try:
        # Get driver version::
        driver_version = LooseVersion(PyMongoVersion)
        # Check driver and server version compatibility:
        check_compatibility(module, srv_version, driver_version)
    except Exception as excep:
        module.fail_json(msg='Unable to authenticate with MongoDB: %s' % to_native(excep))

    try:
        if not zone_exists(client, zone_name):
            module.fail_json(msg="The tag {0} does not exist. You need to associate a tag with a shard before using this module. You can do that with the mongodb_shard_tag module.".format(zone_name))
        else:
            # first check if the ranges exist
            range_count = 0
            if state == "present":
                for range in ranges:
                    if zone_range_exists(client, namespace, range[0], range[1], zone_name):
                        range_count += 1
                result['range_count'] = range_count
                result['ranges'] = len(ranges)
                if range_count == len(ranges):  # All ranges are the same
                    result['changed'] = False
                    result['msg'] = "All Zone Ranges present for {0}".format(zone_name)
                else:
                    for range in ranges:
                        if not module.check_mode:
                            add_zone_range(client, namespace, range[0], range[1], zone_name)
                        result['changed'] = True
                        result['msg'] = "Added zone ranges for {0}".format(zone_name)
            elif state == "absent":
                range_count = zone_range_count(client, zone_name)
                deleted_count = 0
                if range_count > 0 and ranges is None:
                    if not module.check_mode:
                        remove_all_zone_range_by_tag(client, zone_name)
                    deleted_count = range_count
                    result['changed'] = True
                    result['msg'] = "{0} zone ranges for {1} deleted.".format(deleted_count, zone_name)
                elif ranges is not None:
                    for range in ranges:
                        if zone_range_exists(client, namespace, range[0], range[1], zone_name):
                            if not module.check_mode:
                                remove_zone_range(client, namespace, range[0], range[1])
                            deleted_count += 1
                    if deleted_count > 0:
                        result['changed'] = True
                        result['msg'] = "{0} zone ranges for {1} deleted.".format(deleted_count, zone_name)
                    else:
                        result['changed'] = False
                        result['msg'] = "The provided zone ranges are not present for {0}".format(zone_name)
                else:
                    result['changed'] = False
                    result['msg'] = "No zone ranges present for {0}".format(zone_name)
    except Exception as excep:
        module.fail_json(msg="An error occurred: {0}".format(excep))

    module.exit_json(**result)
Exemplo n.º 10
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(mongos_process=dict(type='str',
                                             required=False,
                                             default="mongos"),
                         shard=dict(type='str', required=True),
                         sharded_databases=dict(type="raw", required=False),
                         state=dict(type='str',
                                    required=False,
                                    default='present',
                                    choices=['absent', 'present']))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    ssl = module.params['ssl']
    shard = module.params['shard']
    state = module.params['state']
    sharded_databases = module.params['sharded_databases']
    mongos_process = module.params['mongos_process']

    try:
        connection_params = {"host": login_host, "port": int(login_port)}

        if ssl:
            connection_params = ssl_connection_options(connection_params,
                                                       module)

        client = MongoClient(**connection_params)

        try:
            # Get server version:
            try:
                srv_version = LooseVersion(client.server_info()['version'])
            except Exception as e:
                module.fail_json(
                    msg='Unable to get MongoDB server version: %s' %
                    to_native(e))

            # Get driver version::
            driver_version = LooseVersion(PyMongoVersion)

            # Check driver and server version compatibility:
            check_compatibility(module, srv_version, driver_version)
        except Exception as excep:
            if hasattr(excep, 'code') and excep.code == 13:
                if login_user is not None and login_password is not None:
                    client.admin.authenticate(login_user,
                                              login_password,
                                              source=login_database)
                    check_compatibility(module, client)
                else:
                    raise excep
            else:
                raise excep

        if login_user is None and login_password is None:
            mongocnf_creds = load_mongocnf()
            if mongocnf_creds is not False:
                login_user = mongocnf_creds['user']
                login_password = mongocnf_creds['password']
        elif login_password is None or login_user is None:
            module.fail_json(
                msg=
                'when supplying login arguments, both login_user and login_password must be provided'
            )

        try:
            client['admin'].command(
                'listDatabases',
                1.0)  # if this throws an error we need to authenticate
        except Exception as excep:
            if hasattr(excep, 'code') and excep.code == 13:
                if login_user is not None and login_password is not None:
                    client.admin.authenticate(login_user,
                                              login_password,
                                              source=login_database)
                else:
                    raise excep
            else:
                raise excep

    except Exception as e:
        module.fail_json(msg='unable to connect to database: %s' %
                         to_native(e),
                         exception=traceback.format_exc())

    try:
        if client["admin"].command(
                "serverStatus")["process"] != mongos_process:
            module.fail_json(
                msg="Process running on {0}:{1} is not a {2}".format(
                    login_host, login_port, mongos_process))
        shard_created = False
        dbs_to_shard = []

        if sharded_databases is not None:
            if isinstance(sharded_databases, str):
                sharded_databases = list(sharded_databases)
            dbs_to_shard = any_dbs_to_shard(client, sharded_databases)

        if module.check_mode:
            if state == "present":
                changed = False
                if not shard_find(client, shard) or len(dbs_to_shard) > 0:
                    changed = True
            elif state == "absent":
                if not shard_find(client, shard):
                    changed = False
                else:
                    changed = True
        else:
            if state == "present":
                if not shard_find(client, shard):
                    shard_add(client, shard)
                    changed = True
                else:
                    changed = False
                if len(dbs_to_shard) > 0:
                    for db in dbs_to_shard:
                        enable_database_sharding(client, db)
                    changed = True
            elif state == "absent":
                if shard_find(client, shard):
                    shard_remove(client, shard)
                    changed = True
                else:
                    changed = False
    except Exception as e:
        action = "add"
        if state == "absent":
            action = "remove"
        module.fail_json(msg='Unable to {0} shard: %s'.format(action) %
                         to_native(e),
                         exception=traceback.format_exc())

    result = {
        "changed": changed,
        "shard": shard,
    }
    if len(dbs_to_shard) > 0:
        result['sharded_enabled'] = dbs_to_shard

    module.exit_json(**result)
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(state=dict(type='str',
                                    default='started',
                                    choices=['started', 'stopped']),
                         return_url=dict(type='bool', default=False))

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not has_ordereddict:
        module.fail_json(
            msg=
            'Cannot import OrderedDict class. You can probably install with: pip install ordereddict'
        )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    ssl = module.params['ssl']
    state = module.params['state']
    return_url = module.params['return_url']

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)
    try:
        client = MongoClient(**connection_params)
    except Exception as e:
        module.fail_json(msg='Unable to connect to database: %s' %
                         to_native(e))

    try:
        # If we have auth details use then otherwise attempt without
        if login_user is None and login_password is None:
            mongocnf_creds = load_mongocnf()
            if mongocnf_creds is not False:
                login_user = mongocnf_creds['user']
                login_password = mongocnf_creds['password']
        elif login_password is None or login_user is None:
            module.fail_json(
                msg=
                "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
            )
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(e))

    if login_user is not None and login_password is not None:
        try:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)
        except Exception as excep:
            module.fail_json(msg='Unable to authenticate with MongoDB: %s' %
                             to_native(excep))
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(e))

    # Get driver version::
    driver_version = LooseVersion(PyMongoVersion)

    # Check driver and server version compatibility:
    try:
        check_compatibility(module, srv_version, driver_version)
    except Exception as e:
        module.fail_json(
            msg='Unable to validate MongoDB driver compatibility: %s' %
            to_native(e))

    current_monitoring_state, url = get_monitoring_status(client)
    result = {}
    if state == "started":
        if current_monitoring_state == "started":
            result['changed'] = False
            result['msg'] = "Free monitoring is already started"
        else:
            if module.check_mode is False:
                start_monitoring(client)
            result['changed'] = True
            result['msg'] = "Free monitoring has been started"
    else:
        if current_monitoring_state == "started":
            if module.check_mode is False:
                stop_monitoring(client)
            result['changed'] = True
            result['msg'] = "Free monitoring has been stopped"
        else:
            result['changed'] = False
            result['msg'] = "Free monitoring is already stopped"

    if return_url and url:
        result['url'] = url

    module.exit_json(**result)
Exemplo n.º 12
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        indexes=dict(type='list', elements='raw', required=True),
        replica_set=dict(type='str'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    validate_module(module)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    ssl = module.params['ssl']
    indexes = module.params['indexes']
    replica_set = module.params['replica_set']

    connection_params = {
        'host': login_host,
        'port': login_port,
    }

    if replica_set:
        connection_params["replicaset"] = replica_set

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    client = MongoClient(**connection_params)

    if login_user:
        try:
            client.admin.authenticate(login_user, login_password, source=login_database)
        except Exception as e:
            module.fail_json(msg='Unable to authenticate: %s' % to_native(e))

    # Get server version:
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' % to_native(e))

    # Get driver version::
    driver_version = LooseVersion(PyMongoVersion)

    # Check driver and server version compatibility:
    check_compatibility(module, srv_version, driver_version)

    # Pre flight checks done
    indexes_created = []
    indexes_dropped = []
    changed = None
    for i in indexes:
        try:
            idx = index_exists(client, i["database"], i["collection"], i["options"]["name"])
        except Exception as excep:
            module.fail_json(msg="Could not determine index status: {0}".format(str(excep)))
        if module.check_mode:
            if idx:
                if i["state"] == "present":
                    changed = False
                elif i["state"] == "absent":
                    indexes_dropped.append("{0}.{1}.{2}".format(i["database"],
                                                                i["collection"],
                                                                i["options"]["name"]))
                    changed = True
            else:
                if i["state"] == "present":
                    indexes_created.append("{0}.{1}.{2}".format(i["database"],
                                                                i["collection"],
                                                                i["options"]["name"]))
                    changed = True
                elif i["state"] == "absent":
                    changed = False
        else:
            if idx:
                if i["state"] == "present":
                    changed = False
                elif i["state"] == "absent":
                    try:
                        drop_index(client, i["database"], i["collection"],
                                   i["options"]["name"])
                        indexes_dropped.append("{0}.{1}.{2}".format(i["database"],
                                                                    i["collection"],
                                                                    i["options"]["name"]))
                        changed = True
                    except Exception as excep:
                        module.fail_json(msg="Error dropping index: {0}".format(str(excep)))

            else:
                if i["state"] == "present":
                    try:
                        create_index(client=client,
                                     database=i["database"],
                                     collection=i["collection"],
                                     keys=i["keys"],
                                     options=i["options"])
                        indexes_created.append("{0}.{1}.{2}".format(i["database"],
                                                                    i["collection"],
                                                                    i["options"]["name"]))
                        changed = True
                    except Exception as excep:
                        module.fail_json(msg="Error creating index: {0}".format(str(excep)))
                elif i["state"] == "absent":
                    changed = False

    module.exit_json(changed=changed,
                     indexes_created=indexes_created,
                     indexes_dropped=indexes_dropped)
Exemplo n.º 13
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        maintenance=dict(type='bool', default=False)
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    maintenance = module.params['maintenance']
    ssl = module.params['ssl']

    result = dict(
        changed=False,
    )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as excep:
        module.fail_json(msg='Unable to connect to MongoDB: %s' % to_native(excep))

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(msg="When supplying login arguments, both 'login_user' and 'login_password' must be provided")

    if login_user is not None and login_password is not None:
        try:
            client.admin.authenticate(login_user, login_password, source=login_database)
            # Get server version:
            try:
                srv_version = LooseVersion(client.server_info()['version'])
            except Exception as excep:
                module.fail_json(msg='Unable to get MongoDB server version: %s' % to_native(excep))

            # Get driver version::
            driver_version = LooseVersion(PyMongoVersion)
            # Check driver and server version compatibility:
            check_compatibility(module, srv_version, driver_version)
        except Exception as excep:
            module.fail_json(msg='Unable to authenticate with MongoDB: %s' % to_native(excep))

    try:
        state = member_state(client)
        if state == "PRIMARY":
            result["msg"] = "no action taken as member state was PRIMARY"
        elif state == "SECONDARY":
            if maintenance:
                if module.check_mode:
                    result["changed"] = True
                    result["msg"] = "member was placed into maintenance mode"
                else:
                    put_in_maint_mode(client)
                    result["changed"] = True
                    result["msg"] = "member was placed into maintenance mode"
            else:
                result["msg"] = "No action taken as maintenance parameter is false and member state is SECONDARY"
        elif state == "RECOVERING":
            if maintenance:
                result["msg"] = "no action taken as member is already in a RECOVERING state"
            else:
                if module.check_mode:
                    result["changed"] = True
                    result["msg"] = "the member was removed from maintenance mode"
                else:
                    remove_maint_mode(client)
                    result["changed"] = True
                    result["msg"] = "the member was removed from maintenance mode"
        else:
            result["msg"] = "no action taken as member state was {0}".format(state)
    except Exception as excep:
        module.fail_json(msg='module encountered an error: %s' % to_native(excep))

    module.exit_json(**result)
Exemplo n.º 14
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(replica_set=dict(default=None),
                         param=dict(required=True),
                         value=dict(required=True),
                         param_type=dict(default="str", choices=['str',
                                                                 'int']))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    login_database = module.params['login_database']

    replica_set = module.params['replica_set']
    ssl = module.params['ssl']

    param = module.params['param']
    param_type = module.params['param_type']
    value = module.params['value']

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    # Verify parameter is coherent with specified type
    try:
        if param_type == 'int':
            value = int(value)
    except ValueError:
        module.fail_json(msg="value '%s' is not %s" % (value, param_type))

    try:
        if replica_set:
            client = MongoClient(replicaset=replica_set, **connection_params)
        else:
            client = MongoClient(**connection_params)

        if login_user is None and login_password is None:
            mongocnf_creds = load_mongocnf()
            if mongocnf_creds is not False:
                login_user = mongocnf_creds['user']
                login_password = mongocnf_creds['password']
        elif login_password is None or login_user is None:
            module.fail_json(
                msg=
                'when supplying login arguments, both login_user and login_password must be provided'
            )

        if login_user is not None and login_password is not None:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)

            # Get server version:
            try:
                srv_version = LooseVersion(client.server_info()['version'])
            except Exception as e:
                module.fail_json(
                    msg='Unable to get MongoDB server version: %s' %
                    to_native(e))

            # Get driver version::
            driver_version = LooseVersion(PyMongoVersion)

            # Check driver and server version compatibility:
            check_compatibility(module, srv_version, driver_version)

    except ConnectionFailure as e:
        module.fail_json(msg='unable to connect to database: %s' %
                         to_native(e),
                         exception=traceback.format_exc())

    db = client.admin

    try:
        after_value = db.command("setParameter", **{param: value})
    except OperationFailure as e:
        module.fail_json(msg="unable to change parameter: %s" % to_native(e),
                         exception=traceback.format_exc())

    if "was" not in after_value:
        module.exit_json(
            changed=True,
            msg="Unable to determine old value, assume it changed.")
    else:
        module.exit_json(changed=(value != after_value["was"]),
                         before=after_value["was"],
                         after=value)
Exemplo n.º 15
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        db=dict(type='str', required=True),
        collection=dict(type='str', required=True),
        required=dict(type='list', elements='str'),
        properties=dict(type='dict', default={}),
        action=dict(type='str', choices=['error', 'warn'], default="error"),
        level=dict(type='str',
                   choices=['strict', 'moderate'],
                   default="strict"),
        state=dict(type='str',
                   choices=['present', 'absent'],
                   default='present'),
        debug=dict(type='bool', default=False),
    )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_together=[['login_user',
                                               'login_password']],
                           required_if=[("state", "present", ("db",
                                                              "collection"))])

    if not has_ordereddict:
        module.fail_json(
            msg=
            'Cannot import OrderedDict class. You can probably install with: pip install ordereddict'
        )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    ssl = module.params['ssl']
    db = module.params['db']
    collection = module.params['collection']
    required = module.params['required']
    properties = module.params['properties']
    action = module.params['action']
    level = module.params['level']
    state = module.params['state']
    debug = module.params['debug']

    connection_params = {
        'host': login_host,
        'port': login_port,
    }

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    client = MongoClient(**connection_params)

    if login_user:
        try:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)
        except Exception as e:
            module.fail_json(msg='Unable to authenticate: %s' % to_native(e))

    # Get server version:
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as e:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(e))

    # Get driver version::
    driver_version = LooseVersion(PyMongoVersion)

    # Check driver and server version compatibility:
    check_compatibility(module, srv_version, driver_version)

    result = dict(changed=False, )

    validator = get_validator(client, db, collection)
    if state == "present":
        if validator is not None:
            diff = validator_is_different(client, db, collection, required,
                                          properties, action, level)
            if diff:
                if not module.check_mode:
                    add_validator(client, db, collection, required, properties,
                                  action, level)
                result['changed'] = True
                result[
                    'msg'] = "The validator was updated on the given collection"
            else:
                result['changed'] = False
                result[
                    'msg'] = "The validator exists as configured on the given collection"
        else:
            if not module.check_mode:
                add_validator(client, db, collection, required, properties,
                              action, level)
            result['changed'] = True
            result[
                'msg'] = "The validator has been added to the given collection"
    elif state == "absent":
        if validator is None:
            result['changed'] = False
            result[
                'msg'] = "A validator does not exist on the given collection."
        else:
            if not module.check_mode:
                remove_validator(client, db, collection)
            result['changed'] = True
            result[
                'msg'] = "The validator has been removed from the given collection"

    if debug:
        result['validator'] = validator
        result['module_config'] = {
            "required": required,
            "properties": properties,
            "validationAction": action,
            "validationLevel": level
        }

    module.exit_json(**result)
Exemplo n.º 16
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(compact=dict(type='bool', default=False),
                         oplog_size_mb=dict(type='int', required=True),
                         ver=dict(type='str', default='3.6'))
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    oplog_size_mb = float(
        module.params['oplog_size_mb'])  # MongoDB 4.4 inists on a real
    compact = module.params['compact']
    ver = module.params['ver']
    ssl = module.params['ssl']

    result = dict(changed=False, )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as excep:
        module.fail_json(msg='Unable to connect to MongoDB: %s' %
                         to_native(excep))

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(
            msg=
            "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
        )

    if login_user is not None and login_password is not None:
        try:
            client.admin.authenticate(login_user,
                                      login_password,
                                      source=login_database)
            # Get server version:
            try:
                srv_version = LooseVersion(client.server_info()['version'])
                if srv_version < LooseVersion(ver):
                    module.fail_json(
                        msg="This module does not support MongoDB {0}".format(
                            srv_version))
            except Exception as excep:
                module.fail_json(
                    msg='Unable to get MongoDB server version: %s' %
                    to_native(excep))

            # Get driver version::
            driver_version = LooseVersion(PyMongoVersion)
            # Check driver and server version compatibility:
            check_compatibility(module, srv_version, driver_version)
        except Exception as excep:
            module.fail_json(msg='Unable to authenticate with MongoDB: %s' %
                             to_native(excep))

        try:
            current_oplog_size = get_olplog_size(client)
        except Exception as excep:
            module.fail_json(msg='Unable to get current oplog size: %s' %
                             to_native(excep))
        if oplog_size_mb == current_oplog_size:
            result["msg"] = "oplog_size_mb is already {0} mb".format(
                int(oplog_size_mb))
            result["compacted"] = False
        else:
            try:
                state = member_state(client)
            except Exception as excep:
                module.fail_json(msg='Unable to get member state: %s' %
                                 to_native(excep))
            if module.check_mode:
                result["changed"] = True
                result[
                    "msg"] = "oplog has been resized from {0} mb to {1} mb".format(
                        int(current_oplog_size), int(oplog_size_mb))
                if state == "SECONDARY" and compact and current_oplog_size > oplog_size_mb:
                    result["compacted"] = True
                else:
                    result["compacted"] = False
            else:
                try:
                    set_oplog_size(client, oplog_size_mb)
                    result["changed"] = True
                    result[
                        "msg"] = "oplog has been resized from {0} mb to {1} mb".format(
                            int(current_oplog_size), int(oplog_size_mb))
                except Exception as excep:
                    module.fail_json(msg='Unable to set oplog size: %s' %
                                     to_native(excep))
                if state == "SECONDARY" and compact and current_oplog_size > oplog_size_mb:
                    try:
                        compact_oplog(client)
                        result["compacted"] = True
                    except Exception as excep:
                        module.fail_json(
                            msg='Error compacting member oplog: %s' %
                            to_native(excep))
                else:
                    result["compacted"] = False

    module.exit_json(**result)
Exemplo n.º 17
0
def main():
    argument_spec = mongodb_common_argument_spec()
    argument_spec.update(
        name=dict(type='str', required=True),
        shard=dict(type='str', required=True),
        force=dict(type='bool', default=False),
        mongos_process=dict(type='str', required=False, default="mongos"),
        state=dict(type='str',
                   default="present",
                   choices=["present", "absent"]),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_together=[['login_user', 'login_password']],
    )

    if not has_ordereddict:
        module.fail_json(
            msg=
            'Cannot import OrderedDict class. You can probably install with: pip install ordereddict'
        )

    if not pymongo_found:
        module.fail_json(msg=missing_required_lib('pymongo'),
                         exception=PYMONGO_IMP_ERR)

    login_user = module.params['login_user']
    login_password = module.params['login_password']
    login_database = module.params['login_database']
    login_host = module.params['login_host']
    login_port = module.params['login_port']
    state = module.params['state']
    tag = module.params['name']
    shard = module.params['shard']
    mongos_process = module.params['mongos_process']
    ssl = module.params['ssl']
    force = module.params['force']

    result = dict(changed=False, )

    connection_params = dict(
        host=login_host,
        port=int(login_port),
    )

    if ssl:
        connection_params = ssl_connection_options(connection_params, module)

    try:
        client = MongoClient(**connection_params)
    except Exception as excep:
        module.fail_json(msg='Unable to connect to MongoDB: %s' %
                         to_native(excep))

    if login_user is None and login_password is None:
        mongocnf_creds = load_mongocnf()
        if mongocnf_creds is not False:
            login_user = mongocnf_creds['user']
            login_password = mongocnf_creds['password']
    elif login_password is None or login_user is None:
        module.fail_json(
            msg=
            "When supplying login arguments, both 'login_user' and 'login_password' must be provided"
        )

    try:
        try:
            client['admin'].command(
                'listDatabases',
                1.0)  # if this throws an error we need to authenticate
        except Exception as excep:
            if hasattr(excep, 'code') and excep.code == 13:
                if login_user is not None and login_password is not None:
                    client.admin.authenticate(login_user,
                                              login_password,
                                              source=login_database)
                else:
                    module.fail_json(msg='No credentials to authenticate: %s' %
                                     to_native(excep))
            else:
                module.fail_json(msg='Unknown error: %s' % to_native(excep))
    except Exception as excep:
        module.fail_json(msg='unable to connect to database: %s' %
                         to_native(excep),
                         exception=traceback.format_exc())
    # Get server version:
    try:
        srv_version = LooseVersion(client.server_info()['version'])
    except Exception as excep:
        module.fail_json(msg='Unable to get MongoDB server version: %s' %
                         to_native(excep))
    try:
        # Get driver version::
        driver_version = LooseVersion(PyMongoVersion)
        # Check driver and server version compatibility:
        check_compatibility(module, srv_version, driver_version)
    except Exception as excep:
        module.fail_json(msg='Unable to authenticate with MongoDB: %s' %
                         to_native(excep))

    try:
        if tag_exists(client, shard, tag):
            if state == "present":
                result['changed'] = False
                result[
                    'msg'] = "The tag {0} is already assigned to the shard {1}".format(
                        tag, shard)
            elif state == "absent":
                if not module.check_mode:
                    remove_zone_tag(client, shard, tag)
                result['changed'] = True
                result[
                    'msg'] = "The tag {0} was removed from the shard {1}".format(
                        tag, shard)
        else:
            if state == "present":
                if not module.check_mode:
                    add_zone_tag(client, shard, tag)
                result['changed'] = True
                result[
                    'msg'] = "The tag {0} was assigned to the shard {1}".format(
                        tag, shard)
            elif state == "absent":
                result['changed'] = False
                result[
                    'msg'] = "The tag {0} is not assigned to the shard {1}".format(
                        tag, shard)
    except Exception as excep:
        module.fail_json(msg="An error occurred: {0}".format(excep))

    module.exit_json(**result)