コード例 #1
0
def main():

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        name=dict(type='str', required=True),
        wait_for_active_shards=dict(type='str', default='0'),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']

    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        if client.indices.exists(name):
            response = dict(client.indices.get(name))
            module.exit_json(changed=False,
                             msg="Info about index {0}.".format(name),
                             **response)
        else:
            module.exit_json(changed=False,
                             msg="The index {0} does not exist.".format(name))
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #2
0
def main():

    state_choices = [
        "present",
        "absent"
    ]

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        location=dict(type='str'),
        type=dict(type='str', default='fs'),
        state=dict(type='str', choices=state_choices, default='present'),
        name=dict(type='str', required=True),
        verify=dict(type='bool', default=True)
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    state = module.params['state']

    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        repository = get_snapshot_repository(module, client, name)
        response = None

        if repository is None:
            if state == "present":
                if module.check_mode is False:
                    response = put_repository(module, client, name)
                else:
                    response = {"aknowledged": True}
                module.exit_json(changed=True, msg="The repository {0} was successfully created: {1}".format(name, str(response)))
            elif state == "absent":
                module.exit_json(changed=False, msg="The repository {0} does not exist.".format(name))
        else:
            if state == "present":
                module.exit_json(changed=False, msg="The repository {0} already exists.".format(name))
            elif state == "absent":
                if module.check_mode is False:
                    response = client.snapshot.delete_repository(repository=name)
                else:
                    response = {"aknowledged": True}
                module.exit_json(changed=True, msg="The repository {0} was deleted: {1}".format(name, str(response)))
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #3
0
def main():

    state_choices = [
        "present", "absent", "closed", "opened", "clear_cache", "flush",
        "flush_synced", "refresh", "stats", "upgrade"
    ]

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        name=dict(type='str', required=True),
        state=dict(type='str', choices=state_choices, default='present'),
        settings=dict(type='dict', default={}),
        mappings=dict(type='dict', default={}),
        wait_for_active_shards=dict(type='str', default='0'),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    settings = module.params['settings']
    mappings = module.params['mappings']
    state = module.params['state']

    # TODO main module logic
    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        if state == 'present':
            if client.indices.exists(index=name):
                module.exit_json(
                    changed=False,
                    msg="The index '{0}' already exists.".format(name))
            else:
                request_body = {"settings": settings, "mappings": mappings}
                if module.check_mode:
                    response = {"acknowledged": True}
                else:
                    response = dict(
                        client.indices.create(index=name, body=request_body))
                module.exit_json(
                    changed=True,
                    msg="The index '{0}' was created.".format(name),
                    **response)
        elif state == 'absent':
            if client.indices.exists(index=name):
                if module.check_mode:
                    response = {"acknowledged": True}
                else:
                    response = dict(client.indices.delete(index=name))
                module.exit_json(
                    changed=True,
                    msg="The index '{0}' was deleted.".format(name),
                    **response)
            else:
                module.exit_json(
                    changed=False,
                    msg="The index '{0}' does not exist.".format(name))
        elif state == "closed":
            elastic.index_dynamic_method(module, client, 'close', name)
        elif state == "opened":
            elastic.index_dynamic_method(module, client, 'open', name)
        elif state == "upgrade":
            elastic.index_dynamic_method(module, client, 'upgrade', name)
        elif state == "stats":
            response = dict(client.indices.stats(index=name))
            module.exit_json(changed=True,
                             msg="Stats from index '{0}'.".format(name),
                             **response)
        else:  # Catch all for everything else. Need to make sure the state == method name
            elastic.index_dynamic_method(module, client, state, name)
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #4
0
def main():

    state_choices = ["present", "absent", "started", "stopped"]

    argument_spec = elastic_common_argument_spec()
    # TODO Add options from above
    argument_spec.update(
        name=dict(type='str', required=True),
        index_pattern=dict(type='str'),
        rollup_index=dict(type='str'),
        cron=dict(type='str'),
        page_size=dict(type='int', default=1000),
        groups=dict(type='dict'),
        metrics=dict(type='list', elements='dict'),
        state=dict(type='str', choices=state_choices, default='present'),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    index_pattern = module.params['index_pattern']
    rollup_index = module.params['rollup_index']
    cron = module.params['cron']
    page_size = module.params['page_size']
    groups = module.params['groups']
    metrics = module.params['metrics']
    state = module.params['state']

    # values that should be supplied when passing state = present
    if state == 'present':
        check_param_state_present(module, index_pattern, "index_pattern")
        check_param_state_present(module, rollup_index, "rollup_index")
        check_param_state_present(module, cron, "cron")
        check_param_state_present(module, groups, "groups")
        check_param_state_present(module, metrics, "metrics")
        # Check that groups and metrics has the appropriate keys
        if len(
                set(list(groups.keys())) -
                set(["date_histogram", "histogram", "terms"])) > 0:
            module.fail_json(
                msg="There are invalid keys in the groups dictionary.")
        elif not isinstance(metrics, list):
            module.fail_json(msg="The metrics key does not contain a list.")

    # TODO main module logic
    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        job = get_rollup_job(client, name)

        # We can probably refector this code to reduce by 50% by only chekcing check ode when we actually change something
        if job is not None:  # Job exists
            job_config = job['config']
            job_status = job['status']
            if module.check_mode:
                if state == "present":
                    is_different = job_is_different(job_config, module)
                    if is_different > 0:
                        module.exit_json(
                            changed=True,
                            msg="The rollup job {0} definition was updated. {1}"
                            .format(name, is_different))
                    else:
                        module.exit_json(
                            changed=False,
                            msg=
                            "The rollup job {0} already exists and no updates were needed."
                            .format(name))
                elif state == "absent":
                    module.exit_json(
                        changed=True,
                        msg="The rollup job {0} was removed.".format(name))
                elif state == "started":
                    if job_config["status"]["job_state"] == "stopped":
                        module.exit_json(
                            changed=True,
                            msg="The rollup job {0} was started.".format(name))
                    elif job_config["status"]["job_state"] == "started":
                        module.exit_json(
                            changed=False,
                            msg=
                            "The rollup job {0} is already in a started state".
                            format(name))
                    else:
                        module.fail_jsob(
                            msg="Job {0} was in a unexpected state: {1}.".
                            format(name, state))
                elif state == "stopped":
                    if job_status["job_state"] == "started":
                        module.exit_json(
                            changed=True,
                            msg="The rollup job {0} was stopped.".format(name))
                    elif job_status["job_state"] == "stopped":
                        module.exit_json(
                            changed=False,
                            msg=
                            "The rollup job {0} is already in a stopped state".
                            format(name))
                    else:
                        module.fail_jsob(
                            msg="Job {0} was in a unexpected state: {1}.".
                            format(name, state))
            else:
                if state == "present":
                    is_different = job_is_different(job_config, module)
                    if is_different > 0:
                        module.exit_json(
                            changed=True,
                            msg="The rollup job {0} definition was updated. {1}"
                            .format(name, is_different))
                    else:
                        module.exit_json(
                            changed=False,
                            msg=
                            "The rollup job {0} already exists and no updates were needed."
                            .format(name))
                elif state == "absent":
                    response = client.rollup.delete_job(id=name)
                    module.exit_json(
                        changed=True,
                        msg="The rollup job {0} was removed.".format(name))
                elif state == "started":
                    if job_status["job_state"] == "stopped":
                        client.rollup.start_job(name)
                        module.exit_json(
                            changed=True,
                            msg="The rollup job {0} was started.".format(name))
                    elif job_status["job_state"] == "started":
                        module.exit_json(
                            changed=False,
                            msg=
                            "The rollup job {0} is already in a started state".
                            format(name))
                    else:
                        module.fail_jsob(
                            msg="Job {0} was in a unexpected state: {1}.".
                            format(name, state))
                elif state == "stopped":
                    if job_status["job_state"] == "started":
                        client.rollup.stop_job(name)
                        module.exit_json(
                            changed=True,
                            msg="The rollup job {0} was stopped.".format(name))
                    elif job_status["job_state"] == "stopped":
                        module.exit_json(
                            changed=False,
                            msg=
                            "The rollup job {0} is already in a stopped state".
                            format(name))
                    else:
                        module.fail_jsob(
                            msg="Job {0} was in a unexpected state: {1}.".
                            format(name, state))
        else:
            if module.check_mode:
                if state == "present":
                    module.exit_json(
                        changed=True,
                        msg="The rollup job {0} was created.".format(name))
                elif state == "absent":
                    module.exit_json(
                        changed=False,
                        msg="The rollup job {0} does not exist.".format(name))
                elif state in ["started", "stopped"]:
                    module.exit_json(
                        changed=False,
                        msg="Cannot stop or start a job that does not exist.")
            else:
                if state == "present":
                    body = {
                        "cron": cron,
                        "groups": groups,
                        "index_pattern": index_pattern,
                        "metrics": metrics,
                        "page_size": page_size,
                        "rollup_index": rollup_index
                    }
                    response = client.rollup.put_job(id=name,
                                                     body=body,
                                                     headers=None)
                    module.exit_json(
                        changed=True,
                        msg="The rollup job {0} was successfully created.".
                        format(name))
                elif state == "absent":
                    module.exit_json(
                        changed=False,
                        msg="The rollup job {0} does not exist.".format(name))
                elif state in ["started", "stopped"]:
                    module.exit_json(
                        changed=False,
                        msg="Cannot stop or start a job that does not exist.")

    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #5
0
def main():

    state_choices = ["present", "absent"]

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        applications=dict(type='list', elements='dict'),
        cluster=dict(type='list', elements='str'),
        global_v=dict(type='dict'),
        indices=dict(type='list', elements='dict'),
        metadata=dict(type='dict'),
        name=dict(type='str', required=True),
        run_as=dict(type='list', elements='str'),
        state=dict(type='str', choices=state_choices, default='present'),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    state = module.params['state']

    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        role = get_role(module, client, name)
        response = None

        if role is None:
            if state == "present":
                if module.check_mode is False:
                    response = put_role(module, client, name)
                module.exit_json(
                    changed=True,
                    msg="The role {0} was successfully created: {1}".format(
                        name, str(response)))
            elif state == "absent":
                module.exit_json(
                    changed=False,
                    msg="The role {0} does not exist.".format(name))
        else:
            if state == "present":
                if role_is_different(role, module):
                    if module.check_mode is False:
                        response = put_role(module, client, name)
                    module.exit_json(
                        changed=True,
                        msg="The role {0} was successfully updated: {1}".
                        format(name, str(response)))
                else:
                    module.exit_json(
                        changed=False,
                        msg="The role {0} already exists as configured.".
                        format(name))
            elif state == "absent":
                if module.check_mode is False:
                    response = client.security.delete_role(
                        name=name)  # TODO Check ack key?
                    module.exit_json(
                        changed=True,
                        msg="The role {0} was deleted.".format(name))
                else:
                    module.exit_json(
                        changed=True,
                        msg="The role {0} was deleted.".format(name))
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #6
0
def main():
    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        persistent=dict(type='bool', default=True),
        settings=dict(type='dict', required=True),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    persistent = module.params['persistent']
    settings = module.params['settings']

    # TODO main module logic
    try:
        if persistent:
            settings_doc = {"persistent": settings}
        else:
            settings_doc = {"transient": settings}

        elastic = ElasticHelpers(module)
        client = elastic.connect()

        current_settings = cluster_get_settings(client)

        if persistent:
            del current_settings['transient']
        else:
            del current_settings['persistent']

        # Fail if we have any unexpected keys
        if len(
                list(
                    set(current_settings.keys()) -
                    set(['persistent', 'transient', 'defaults']))) > 0:
            unexpected_keys = list(
                set(current_settings.keys()) -
                set(['persistent', 'transient', 'defaults']))
            module.fail_json(
                msg="Unexpected key found in cluster config: {0}".format(
                    str(unexpected_keys)))

        cluster_configuration_changes = {}
        selected_key = list(settings_doc.keys())[0]
        none_debug = False
        for config_item in list(settings_doc[selected_key].keys()):
            desired_value = None
            actual_value = None
            if settings_doc[selected_key][config_item] is None \
                    and config_item in list(current_settings[selected_key].keys()):
                cluster_configuration_changes[config_item] = {
                    "old_value": None,
                    "new_value": "<default>"
                }
            elif settings_doc[selected_key][config_item] == \
                    current_settings[selected_key].get(config_item):
                pass
            elif settings_doc[selected_key][config_item] == \
                    current_settings["defaults"].get(config_item):
                pass
            else:
                # If we reach here the value results in a cluster settings change
                desired_value = settings_doc[selected_key][config_item]
                actual_value = current_settings[selected_key].get(config_item)
                if actual_value is None:
                    actual_value = current_settings["defaults"].get(
                        config_item)
                cluster_configuration_changes[config_item] = {
                    "old_value": actual_value,
                    "new_value": desired_value
                }

        if none_debug:
            module.exit_json(**cluster_configuration_changes)

        if cluster_configuration_changes == {}:
            module.exit_json(
                changed=False,
                msg="There are no cluster configuration changes to perform.")
        else:
            if module.check_mode:
                module.exit_json(
                    changed=True,
                    msg="The cluster configuration has been updated.",
                    cluster_cfg_changes=cluster_configuration_changes)
            else:
                response = cluster_put_settings(client, body=settings_doc)
                if response['acknowledged']:
                    module.exit_json(
                        changed=True,
                        msg="The cluster configuration has been updated.",
                        cluster_cfg_changes=cluster_configuration_changes)
                else:
                    module.fail_json(
                        msg="Something has gone wrong: {0}".format(
                            str(response)))
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #7
0
def main():

    state_choices = ["present", "absent", "restore"]

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(indices=dict(type='list', elements='str'),
                         ignore_unavailable=dict(type='bool', default=False),
                         repository=dict(type='str', required=True),
                         state=dict(type='str',
                                    choices=state_choices,
                                    default='present'),
                         metadata=dict(type='str'),
                         name=dict(type='str', required=True),
                         partial=dict(type='bool', default=False))

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    repository = module.params['repository']
    state = module.params['state']

    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        snapshot = get_snapshot(module, client, repository, name)
        response = None

        if snapshot is None:
            if state == "present":
                if module.check_mode is False:
                    response = create_snapshot(module, client, repository,
                                               name)
                else:
                    response = {"acknowledged": True}
                module.exit_json(
                    changed=True,
                    msg="The snapshot {0} was successfully created: {1}".
                    format(name, str(response)))
            elif state == "absent":
                module.exit_json(
                    changed=False,
                    msg="The snapshot {0} does not exist.".format(name))
            elif state == "restore":
                module.fail_json(
                    msg="Cannot restore a snapshot that does not exist: {0}".
                    format(name))
        else:
            if state == "present":
                module.exit_json(
                    changed=False,
                    msg="The snapshot {0} already exists.".format(name))
            elif state == "absent":
                if module.check_mode is False:
                    response = client.snapshot.delete(repository=repository,
                                                      snapshot=name)
                else:
                    response = {"acknowledged": True}
                module.exit_json(
                    changed=True,
                    msg="The snapshot {0} was deleted: {1}".format(
                        name, str(response)))
            elif state == "restore":
                if module.check_mode is False:
                    response = restore_snapshot(module, client, repository,
                                                name)
                else:
                    response = {"acknowledged": True}
                module.exit_json(
                    changed=True,
                    msg="The snapshot {0} was restored: {1}".format(
                        name, str(response)))
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #8
0
def main():

    state_choices = [
        "present",
        "absent"
    ]

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        enabled=dict(type='bool', default=True),
        email=dict(type='str'),
        full_name=dict(type='str'),
        metadata=dict(type='dict', default={}),
        password=dict(type='str', no_log=True),
        roles=dict(type='list', elements='str'),
        name=dict(type='str', required=True),
        run_as=dict(type='list', elements='str'),
        state=dict(type='str', choices=state_choices, default='present'),
        update_password=dict(type='str', choices=['always', 'on_create'], default='always', no_log=True)
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    state = module.params['state']
    update_password = module.params['update_password']

    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        user = get_user(module, client, name)
        response = None

        if user is None:
            if state == "present":
                if module.check_mode is False:
                    response = put_user(module, client, name)
                module.exit_json(changed=True, msg="The user {0} was successfully created: {1}".format(name, str(response)))
            elif state == "absent":
                module.exit_json(changed=False, msg="The user {0} does not exist.".format(name))
        else:
            if state == "present":
                if user_is_different(user, module) or update_password == "always":
                    if module.check_mode is False:
                        response = put_user(module, client, name)
                    module.exit_json(changed=True, msg="The user {0} was successfully updated: {1} {2}".format(name, str(response), str(user)))
                else:
                    module.exit_json(changed=False, msg="The user {0} already exists as configured.".format(name))
            elif state == "absent":
                if module.check_mode is False:
                    response = client.security.delete_user(username=name)
                    module.exit_json(changed=True, msg="The user {0} was deleted.".format(name))
                else:
                    module.exit_json(changed=True, msg="The user {0} was deleted.".format(name))
    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #9
0
def main():

    argument_spec = elastic_common_argument_spec()
    argument_spec.update(
        source=dict(type='str', required=True),
        dest=dict(type='str', required=True),
        wait_for_completion=dict(type='bool', default=False),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    source = module.params['source']
    dest = module.params['dest']
    wait_for_completion = module.params['wait_for_completion']

    try:

        elastic = ElasticHelpers(module)
        client = elastic.connect()

        result = dict(
            client.reindex(
                {
                    "source": {
                        "index": source
                    },
                    "dest": {
                        "index": dest
                    }
                },
                wait_for_completion=wait_for_completion))
        if isinstance(result, dict) and 'task' in list(result.keys()):
            msg = "The copy task from {0} to {1} has been started.".format(
                source, dest)
            module.exit_json(changed=True, msg=msg, **result)
        elif isinstance(result, dict) and 'took' in list(result.keys()):
            msg = "The copy from {0} to {1} was successful.".format(
                source, dest)
            module.exit_json(changed=True,
                             msg=msg,
                             created=result['created'],
                             updated=result['updated'],
                             deleted=result['deleted'],
                             failed=len(result['failures']),
                             took=result['took'],
                             batches=result['batches'])
        else:
            msg = "Copy failed."
            if result is None:
                result = {}
            module.fail_json(changed=True, msg=msg, **result)

    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #10
0
def main():

    state_choices = ["present", "absent"]

    argument_spec = elastic_common_argument_spec()
    # TODO Add options from above
    argument_spec.update(
        name=dict(type='str', required=True, aliases=['pipeline_id']),
        description=dict(type='str'),
        processors=dict(type='list', elements='dict'),
        version=dict(type='int'),
        state=dict(type='str', choices=state_choices, default='present'),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    state = module.params['state']

    # values that should be supplied when passing state = present
    if state == 'present':
        check_param_state_present(module, "processors")
    #    check_param_state_present(module, cron, "cron")
    #    check_param_state_present(module, groups, "groups")
    #    check_param_state_present(module, metrics, "metrics")
    # Check that groups and metrics has the appropriate keys
    #    if len(set(list(groups.keys())) - set(["date_histogram", "histogram", "terms"])) > 0:
    #        module.fail_json(msg="There are invalid keys in the groups dictionary.")
    #    elif not isinstance(metrics, list):
    #        module.fail_json(msg="The metrics key does not contain a list.")

    # TODO main module logic
    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        pipeline = get_pipeline(client, name)

        # We can probably refector this code to reduce by 50% by only checking when we actually change something
        if pipeline is not None:  # pipeline exists
            if module.check_mode:
                if state == "present":
                    is_different = pipeline_is_different(pipeline, module)
                    if is_different > 0:
                        module.exit_json(
                            changed=True,
                            msg="The pipeline {0} definition was updated. {1}".
                            format(name, is_different))
                    else:
                        module.exit_json(
                            changed=False,
                            msg=
                            "The pipeline {0} already exists and no updates were needed."
                            .format(name))
                elif state == "absent":
                    module.exit_json(
                        changed=True,
                        msg="The pipeline {0} was removed.".format(name))
            else:
                if state == "present":
                    is_different = pipeline_is_different(pipeline, module)
                    if is_different > 0:
                        module.exit_json(
                            changed=True,
                            msg="The pipeline {0} definition was updated. {1}".
                            format(name, is_different))
                    else:
                        module.exit_json(
                            changed=False,
                            msg=
                            "The pipeline {0} already exists and no updates were needed."
                            .format(name))
                elif state == "absent":
                    response = client.ingest.delete_pipeline(id=name)
                    module.exit_json(
                        changed=True,
                        msg="The pipeline {0} was removed.".format(name))
        else:
            if module.check_mode:
                if state == "present":
                    module.exit_json(
                        changed=True,
                        msg="The pipeline {0} was successfully created.".
                        format(name))
                elif state == "absent":
                    module.exit_json(
                        changed=False,
                        msg="The pipeline {0} does not exist.".format(name))
            else:
                if state == "present":
                    body = {}
                    body_keys = ["description", "processors", "version"]
                    for key in body_keys:
                        body = add_if_not_none(body, key, module)
                    response = client.ingest.put_pipeline(id=name,
                                                          body=body,
                                                          headers=None)
                    module.exit_json(
                        changed=True,
                        msg="The pipeline {0} was successfully created.".
                        format(name))
                elif state == "absent":
                    module.exit_json(
                        changed=False,
                        msg="The pipeline {0} does not exist.".format(name))

    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))
コード例 #11
0
def main():

    state_choices = [
        "present",
        "absent",
        "started",
        "stopped"
    ]

    argument_spec = elastic_common_argument_spec()
    # TODO Add options from above
    argument_spec.update(
        name=dict(type='str', required=True, aliases=['transform_id']),
        defer_validation=dict(type='bool', default=False),
        description=dict(type='str'),
        dest=dict(type='dict'),
        frequency=dict(type='str', default="1m"),
        latest=dict(type='dict'),
        pivot=dict(type='dict'),
        settings=dict(type='dict'),
        source=dict(type='dict'),
        sync=dict(type='dict'),
        state=dict(type='str', choices=state_choices, default='present'),
    )

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

    if not elastic_found:
        module.fail_json(msg=missing_required_lib('elasticsearch'),
                         exception=E_IMP_ERR)

    name = module.params['name']
    state = module.params['state']

    # values that should be supplied when passing state = present
    if state == 'present':
        check_param_state_present(module, "dest")
        check_param_state_present(module, "source")
    #    check_param_state_present(module, cron, "cron")
    #    check_param_state_present(module, groups, "groups")
    #    check_param_state_present(module, metrics, "metrics")
    # Check that groups and metrics has the appropriate keys
    #    if len(set(list(groups.keys())) - set(["date_histogram", "histogram", "terms"])) > 0:
    #        module.fail_json(msg="There are invalid keys in the groups dictionary.")
    #    elif not isinstance(metrics, list):
    #        module.fail_json(msg="The metrics key does not contain a list.")

    # TODO main module logic
    try:
        elastic = ElasticHelpers(module)
        client = elastic.connect()

        job = get_transform_job(client, name)

        # We can probably refector this code to reduce by 50% by only checking when we actually change something
        if job is not None:  # Job exists
            job_config = job
            job_status = get_transform_state(client, name)
            if module.check_mode:
                if state == "present":
                    is_different = job_is_different(job_config, module)
                    if is_different > 0:
                        module.exit_json(changed=True, msg="The transform job {0} definition was updated. {1}".format(name, is_different))
                    else:
                        module.exit_json(changed=False, msg="The transform job {0} already exists and no updates were needed.".format(name))
                elif state == "absent":
                    module.exit_json(changed=True, msg="The transform job {0} was removed.".format(name))
                elif state == "started":
                    if job_config["status"]["job_state"] == "stopped":
                        module.exit_json(changed=True, msg="The transform job {0} was started.".format(name))
                    elif job_config["status"]["job_state"] == "started":
                        module.exit_json(changed=False, msg="The transform job {0} is already in a started state".format(name))
                    else:
                        module.fail_jsob(msg="Job {0} was in a unexpected state: {1}.".format(name, state))
                elif state == "stopped":
                    if job_status == "started":
                        module.exit_json(changed=True, msg="The transform job {0} was stopped.".format(name))
                    elif job_status == "stopped":
                        module.exit_json(changed=False, msg="The transform job {0} is already in a stopped state".format(name))
                    else:
                        module.fail_jsob(msg="Job {0} was in a unexpected state: {1}.".format(name, state))
            else:
                if state == "present":
                    is_different = job_is_different(job_config, module)
                    if is_different > 0:
                        module.exit_json(changed=True, msg="The transform job {0} definition was updated. {1}".format(name, is_different))
                    else:
                        module.exit_json(changed=False, msg="The transform job {0} already exists and no updates were needed.".format(name))
                elif state == "absent":
                    response = client.transform.delete_transform(transform_id=name)
                    module.exit_json(changed=True, msg="The transform job {0} was removed.".format(name))
                elif state == "started":
                    if job_status == "stopped":
                        client.transform.start_transform(transform_id=name)
                        module.exit_json(changed=True, msg="The transform job {0} was started.".format(name))
                    elif job_status == "started":
                        module.exit_json(changed=False, msg="The transform job {0} is already in a started state".format(name))
                    else:
                        module.fail_jsob(msg="Job {0} was in a unexpected state: {1}.".format(name, state))
                elif state == "stopped":
                    if job_status == "started":
                        client.transform.stop_transform(transform_id=name)
                        module.exit_json(changed=True, msg="The transform job {0} was stopped.".format(name))
                    elif job_status == "stopped":
                        module.exit_json(changed=False, msg="The transform job {0} is already in a stopped state".format(name))
                    else:
                        module.fail_jsob(msg="Job {0} was in a unexpected state: {1}.".format(name, state))
        else:
            if module.check_mode:
                if state == "present":
                    module.exit_json(changed=True, msg="The transform job {0} was created.".format(name))
                elif state == "absent":
                    module.exit_json(changed=False, msg="The transform job {0} does not exist.".format(name))
                elif state in ["started", "stopped"]:
                    module.exit_json(changed=False, msg="Cannot stop or start a job that does not exist.")
            else:
                if state == "present":
                    body = {}
                    body_keys = [
                        "description",
                        "dest",
                        "frequency",
                        "latest",
                        "pivot",
                        "settings",
                        "source",
                        "sync"
                    ]
                    for key in body_keys:
                        body = add_if_not_none(body, key, module)
                    response = client.transform.put_transform(transform_id=name,
                                                              body=body,
                                                              headers=None,
                                                              defer_validation=module.params['defer_validation'])
                    module.exit_json(changed=True, msg="The transform job {0} was successfully created.".format(name))
                elif state == "absent":
                    module.exit_json(changed=False, msg="The transform job {0} does not exist.".format(name))
                elif state in ["started", "stopped"]:
                    module.exit_json(changed=False, msg="Cannot stop or start a job that does not exist.")

    except Exception as excep:
        module.fail_json(msg='Elastic error: %s' % to_native(excep))