Ejemplo n.º 1
0
    def test_abort_on_invalid_status(self, mocker, status):
        client = mocker.Mock()
        client.get.return_value = http.Response(status, "")

        with pytest.raises(errors.SyncError, match=str(status)):
            utils.get(client, "/get")
        client.get.assert_called_once_with("/get")
Ejemplo n.º 2
0
    def test_abort_on_invalid_json(self, mocker):
        client = mocker.Mock()
        client.get.return_value = http.Response(200, "")

        with pytest.raises(errors.SyncError, match="JSON"):
            utils.get(client, "/get")
        client.get.assert_called_once_with("/get")
Ejemplo n.º 3
0
def sync(state, client, list_path, resource_path, payload, check_mode):
    datastore = utils.get(client, resource_path)

    # When we are deleting stores, we do not care if there is more than one
    # datastore present. We just make sure the currently manipulated store is
    # gone. This makes our module useful in "let us clean up the mess"
    # scenarios.
    if state == "absent" and datastore is None:
        return False, None

    if state == "absent":
        if not check_mode:
            utils.delete(client, resource_path)
        return True, None

    # If the store exists, update it and ignore the fact that there might be
    # more than one present.
    if datastore:
        if _do_differ(datastore, payload):
            if check_mode:
                return True, payload
            utils.put(client, resource_path, payload)
            return True, utils.get(client, resource_path)
        return False, datastore

    # When adding a new datastore, we first make sure there is no other
    # datastore present because we do not want to be the ones who brought
    # backends into an inconsistent state.
    if utils.get(client, list_path):
        raise errors.Error("Some other external datastore is already active.")

    if check_mode:
        return True, payload
    utils.put(client, resource_path, payload)
    return True, utils.get(client, resource_path)
Ejemplo n.º 4
0
def sync(remote_object, state, client, path, payload, check_mode):
    if state == 'disabled' and remote_object is not None:
        if not check_mode:
            utils.delete(client, path)
        return True, utils.get(client, path)

    if utils.do_differ(remote_object, payload):
        if check_mode:
            return True, payload
        utils.put(client, path, payload)
        return True, utils.get(client, path)

    return False, remote_object
Ejemplo n.º 5
0
def sync(remote_object, client, path, payload, check_mode):
    # Create new user (either enabled or disabled)
    if remote_object is None:
        if check_mode:
            return True, payload
        utils.put(client, path, payload)
        return True, utils.get(client, path)

    # Update existing user. We do this on a field-by-field basis because the
    # upsteam API for updating users requires a password field to be set. Of
    # course, we do not want to force users to specify an existing password
    # just for the sake of updating the group membership, so this is why we
    # use field-specific API endpoints to update the user data.

    changed = False
    if 'password' in payload:
        changed = update_password(
            client,
            path,
            payload['username'],
            payload['password'],
            check_mode,
        ) or changed

    if 'groups' in payload:
        changed = update_groups(
            client,
            path,
            remote_object.get('groups') or [],
            payload['groups'],
            check_mode,
        ) or changed

    if 'disabled' in payload:
        changed = update_state(
            client,
            path,
            remote_object['disabled'],
            payload['disabled'],
            check_mode,
        ) or changed

    if check_mode:
        # Backend does not return back passwords, so we should follow the
        # example set by the backend API.
        return changed, dict(
            remote_object,
            **{k: v
               for k, v in payload.items() if k != 'password'})

    return changed, utils.get(client, path)
Ejemplo n.º 6
0
def main():
    required_by = {'check': ['entity']}
    module = AnsibleModule(
        supports_check_mode=True,
        required_by=required_by,
        argument_spec=dict(
            arguments.get_spec("auth", "namespace"),
            check=dict(),
            entity=dict(),
        ),
    )

    client = arguments.get_sensu_client(module.params['auth'])
    path = utils.build_core_v2_path(
        module.params['namespace'],
        'events',
        module.params['entity'],
        module.params['check'],
    )

    try:
        events = utils.prepare_result_list(utils.get(client, path))
    except errors.Error as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=events)
Ejemplo n.º 7
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.get_spec('auth', 'namespace'),
            subscription=dict(),
            check=dict(),
        ),
    )

    name = '{0}:{1}'.format(module.params['subscription'] or '*',
                            module.params['check'] or '*')
    client = arguments.get_sensu_client(module.params["auth"])
    path = utils.build_core_v2_path(
        module.params["namespace"],
        "silenced",
        None if name == "*:*" else name,
    )

    try:
        silences = utils.prepare_result_list(utils.get(client, path))
    except errors.Error as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=silences)
Ejemplo n.º 8
0
def main():
    required_if = [('state', 'enabled', ('password', ))]
    module = AnsibleModule(
        required_if=required_if,
        supports_check_mode=True,
        argument_spec=dict(arguments.get_spec("auth", "name"),
                           state=dict(
                               default='enabled',
                               choices=['enabled', 'disabled'],
                           ),
                           password=dict(no_log=True),
                           groups=dict(type='list', )),
    )

    client = arguments.get_sensu_client(module.params['auth'])
    path = utils.build_core_v2_path(None, 'users', module.params['name'])
    state = module.params['state']

    remote_object = utils.get(client, path)
    if remote_object is None and state == 'disabled' and module.params[
            'password'] is None:
        module.fail_json(msg='Cannot disable a non existent user')

    payload = arguments.get_spec_payload(module.params, 'password', 'groups')
    payload['username'] = module.params['name']
    payload['disabled'] = module.params['state'] == 'disabled'

    try:
        changed, user = sync(remote_object, state, client, path, payload,
                             module.check_mode)
        module.exit_json(changed=changed, object=user)
    except errors.Error as e:
        module.fail_json(msg=str(e))
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.get_spec("auth"),
            name=dict(),  # Name is not required in info modules.
        ),
    )

    client = arguments.get_sensu_client(module.params["auth"])
    path = utils.build_url_path(
        API_GROUP,
        API_VERSION,
        None,
        "provider",
        module.params["name"],
    )

    try:
        stores = utils.prepare_result_list(utils.get(client, path))
    except errors.Error as e:
        module.fail_json(msg=str(e))

    # We simulate the behavior of v2 API here and only return the spec.
    module.exit_json(
        changed=False,
        objects=[utils.convert_v1_to_v2_response(s) for s in stores])
Ejemplo n.º 10
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.get_spec('auth'),
            subscription=dict(),
            check=dict(),
        ),
    )

    name = '{0}:{1}'.format(module.params['subscription'] or '*',
                            module.params['check'] or '*')
    client = arguments.get_sensu_client(module.params["auth"])
    if name != '*:*':
        path = "/silenced/{0}".format(name)
    else:
        path = "/silenced"

    try:
        silences = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    if name != '*:*':
        silences = [silences]
    module.exit_json(changed=False, objects=silences)
Ejemplo n.º 11
0
    def test_ignore_invalid_json_on_404(self, mocker):
        client = mocker.Mock()
        client.get.return_value = http.Response(404, "")

        object = utils.get(client, "/get")

        assert object is None
        client.get.assert_called_once_with("/get")
Ejemplo n.º 12
0
    def test_valid_json(self, mocker):
        client = mocker.Mock()
        client.get.return_value = http.Response(200, '{"get": "data"}')

        object = utils.get(client, "/get")

        assert {"get": "data"} == object
        client.get.assert_called_once_with("/get")
Ejemplo n.º 13
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(arguments.get_spec("auth"), ),
    )
    client = arguments.get_sensu_client(module.params['auth'])
    path = utils.build_core_v2_path(None, 'namespaces')

    try:
        namespaces = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=namespaces)
Ejemplo n.º 14
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.get_spec("auth", "name"),
            state=dict(
                default='enabled',
                choices=['enabled', 'disabled'],
            ),
            password=dict(
                no_log=True
            ),
            groups=dict(
                type='list', elements='str',
            )
        ),
    )

    client = arguments.get_sensu_client(module.params['auth'])
    path = utils.build_core_v2_path(None, 'users', module.params['name'])

    try:
        if not HAS_BCRYPT and client.version >= "5.21.0":
            module.fail_json(
                msg=missing_required_lib('bcrypt'),
                exception=BCRYPT_IMPORT_ERROR,
            )
    except errors.SensuError as e:
        module.fail_json(msg=str(e))

    try:
        remote_object = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    if remote_object is None and module.params['password'] is None:
        module.fail_json(msg='Cannot create new user without a password')

    payload = arguments.get_spec_payload(module.params, 'password', 'groups')
    payload['username'] = module.params['name']
    payload['disabled'] = module.params['state'] == 'disabled'

    try:
        changed, user = sync(
            remote_object, client, path, payload, module.check_mode
        )
        module.exit_json(changed=changed, object=user)
    except errors.Error as e:
        module.fail_json(msg=str(e))
Ejemplo n.º 15
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(arguments.COMMON_ARGUMENTS, ),
    )
    module.params['auth']['namespace'] = None
    client = arguments.get_sensu_client(module.params['auth'])
    path = '/namespaces'

    try:
        namespaces = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=namespaces)
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.get_spec("auth"),
            name=dict(),  # Name is not required in info modules.
        ),
    )
    client = arguments.get_sensu_client(module.params["auth"])
    path = utils.build_core_v2_path(None, "users", module.params["name"])

    try:
        users = utils.prepare_result_list(utils.get(client, path))
    except errors.Error as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=users)
Ejemplo n.º 17
0
def main():
    module = AnsibleModule(supports_check_mode=True,
                           argument_spec=dict(arguments.get_spec("auth"),
                                              name=dict()))

    client = arguments.get_sensu_client(module.params["auth"])
    if module.params["name"]:
        path = "/rolebindings/{0}".format(module.params["name"])
    else:
        path = "/rolebindings"

    try:
        role_bindings = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    if module.params["name"]:
        role_bindings = [role_bindings]
    module.exit_json(changed=False, objects=role_bindings)
Ejemplo n.º 18
0
def main():
    module = AnsibleModule(supports_check_mode=True,
                           argument_spec=dict(arguments.get_spec("auth"),
                                              name=dict()))

    client = arguments.get_sensu_client(module.params["auth"])
    path = utils.build_core_v2_path(
        None,
        "clusterrolebindings",
        module.params["name"],
    )

    try:
        cluster_role_bindings = utils.prepare_result_list(
            utils.get(client, path))
    except errors.Error as e:
        module.fail_json(msg=str(e))

    module.exit_json(changed=False, objects=cluster_role_bindings)
Ejemplo n.º 19
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(arguments.get_spec("auth"), name=dict()),
    )

    module.params['auth'][
        'namespace'] = None  # Making sure we are not fallbacking to default
    client = arguments.get_sensu_client(module.params["auth"])
    if module.params["name"]:
        path = "/clusterroles/{0}".format(module.params["name"])
    else:
        path = "/clusterroles"

    try:
        cluster_roles = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    if module.params["name"]:
        cluster_roles = [cluster_roles]
    module.exit_json(changed=False, objects=cluster_roles)
Ejemplo n.º 20
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.COMMON_ARGUMENTS,
            name=dict(),
        ),
    )

    client = arguments.get_sensu_client(module.params["auth"])
    if module.params["name"]:
        path = "/hooks/{0}".format(module.params["name"])
    else:
        path = "/hooks"

    try:
        hooks = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    if module.params["name"]:
        hooks = [hooks]
    module.exit_json(changed=False, objects=hooks)
Ejemplo n.º 21
0
def main():
    module = AnsibleModule(
        supports_check_mode=True,
        argument_spec=dict(
            arguments.get_spec("auth"),
            name=dict(),  # Name is not required in info modules.
        ),
    )

    client = arguments.get_sensu_client(module.params["auth"])
    if module.params["name"]:
        path = "/entities/{0}".format(module.params["name"])
    else:
        path = "/entities"

    try:
        entities = utils.get(client, path)
    except errors.Error as e:
        module.fail_json(msg=str(e))

    if module.params["name"]:
        entities = [entities]
    module.exit_json(changed=False, objects=entities)
Ejemplo n.º 22
0
def send_event(client, path, payload, check_mode):
    if check_mode:
        return True, payload
    utils.put(client, path, payload)
    return True, utils.get(client, path)
Ejemplo n.º 23
0
def _get(client, path):
    return utils.convert_v1_to_v2_response(utils.get(client, path))