def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
    argument_spec = dict(
        src=dict(type="path"),
        replace_src=dict(),
        lines=dict(aliases=["commands"], type="list"),
        parents=dict(type="list"),
        before=dict(type="list"),
        after=dict(type="list"),
        match=dict(default="line", choices=["line", "strict", "exact",
                                            "none"]),
        replace=dict(default="line", choices=["line", "block", "config"]),
        running_config=dict(aliases=["config"]),
        intended_config=dict(),
        defaults=dict(type="bool", default=False),
        backup=dict(type="bool", default=False),
        backup_options=dict(type="dict", options=backup_spec),
        save_when=dict(choices=["always", "never", "modified", "changed"],
                       default="never"),
        diff_against=dict(choices=["running", "startup", "intended"]),
        diff_ignore_lines=dict(type="list"),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [("lines", "src", "replace_src"), ("parents", "src")]

    required_if = [
        ("match", "strict", ["lines"]),
        ("match", "exact", ["lines"]),
        ("replace", "block", ["lines"]),
        ("replace", "config", ["replace_src"]),
        ("diff_against", "intended", ["intended_config"]),
    ]

    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=mutually_exclusive,
        required_if=required_if,
        supports_check_mode=True,
    )

    warnings = list()

    result = {"changed": False, "warnings": warnings}

    config = None

    diff_ignore_lines = module.params["diff_ignore_lines"]
    path = module.params["parents"]
    connection = get_connection(module)
    contents = None
    flags = ["all"] if module.params["defaults"] else []
    replace_src = module.params["replace_src"]
    if replace_src:
        if module.params["replace"] != "config":
            module.fail_json(
                msg="replace: config is required with replace_src")

    if module.params["backup"] or (module._diff and
                                   module.params["diff_against"] == "running"):
        contents = get_config(module, flags=flags)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params["backup"]:
            result["__backup__"] = contents

    if any((module.params["src"], module.params["lines"], replace_src)):
        match = module.params["match"]
        replace = module.params["replace"]

        commit = not module.check_mode
        candidate = get_candidate(module)
        running = get_running_config(module, contents, flags=flags)
        if replace_src:
            commands = candidate.split("\n")
            result["commands"] = result["updates"] = commands
            if commit:
                load_config(module, commands, replace=replace_src)

            result["changed"] = True
        else:
            try:
                response = connection.get_diff(
                    candidate=candidate,
                    running=running,
                    diff_match=match,
                    diff_ignore_lines=diff_ignore_lines,
                    path=path,
                    diff_replace=replace,
                )
            except ConnectionError as exc:
                module.fail_json(
                    msg=to_text(exc, errors="surrogate_then_replace"))

            config_diff = response["config_diff"]
            if config_diff:
                commands = config_diff.split("\n")

                if module.params["before"]:
                    commands[:0] = module.params["before"]

                if module.params["after"]:
                    commands.extend(module.params["after"])

                result["commands"] = commands
                result["updates"] = commands

                if commit:
                    load_config(module, commands, replace=replace_src)

                result["changed"] = True

    running_config = module.params["running_config"]
    startup_config = None

    if module.params["save_when"] == "always":
        save_config(module, result)
    elif module.params["save_when"] == "modified":
        output = execute_show_commands(
            module, ["show running-config", "show startup-config"])

        running_config = NetworkConfig(indent=2,
                                       contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(indent=2,
                                       contents=output[1],
                                       ignore_lines=diff_ignore_lines)

        if running_config.sha1 != startup_config.sha1:
            save_config(module, result)
    elif module.params["save_when"] == "changed" and result["changed"]:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = execute_show_commands(module, "show running-config")
            contents = output[0]
        else:
            contents = running_config

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=2,
                                       contents=contents,
                                       ignore_lines=diff_ignore_lines)

        if module.params["diff_against"] == "running":
            if module.check_mode:
                module.warn(
                    "unable to perform diff against running-config due to check mode"
                )
                contents = None
            else:
                contents = config.config_text

        elif module.params["diff_against"] == "startup":
            if not startup_config:
                output = execute_show_commands(module, "show startup-config")
                contents = output[0]
            else:
                contents = startup_config.config_text

        elif module.params["diff_against"] == "intended":
            contents = module.params["intended_config"]

        if contents is not None:
            base_config = NetworkConfig(indent=2,
                                        contents=contents,
                                        ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                if module.params["diff_against"] == "intended":
                    before = running_config
                    after = base_config
                elif module.params["diff_against"] in ("startup", "running"):
                    before = base_config
                    after = running_config

                result.update({
                    "changed": True,
                    "diff": {
                        "before": str(before),
                        "after": str(after)
                    },
                })

    module.exit_json(**result)
Esempio n. 2
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type='path'))
    argument_spec = dict(
        src=dict(type='path'),
        replace_src=dict(),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(choices=['running', 'startup', 'intended']),
        diff_ignore_lines=dict(type='list'),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [('lines', 'src', 'replace_src'), ('parents', 'src')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['replace_src']),
                   ('diff_against', 'intended', ['intended_config'])]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           required_if=required_if,
                           supports_check_mode=True)

    warnings = list()

    result = {'changed': False, 'warnings': warnings}

    config = None

    diff_ignore_lines = module.params['diff_ignore_lines']
    path = module.params['parents']
    connection = get_connection(module)
    contents = None
    flags = ['all'] if module.params['defaults'] else []
    replace_src = module.params['replace_src']
    if replace_src:
        if module.params['replace'] != 'config':
            module.fail_json(
                msg='replace: config is required with replace_src')

    if module.params['backup'] or (module._diff and
                                   module.params['diff_against'] == 'running'):
        contents = get_config(module, flags=flags)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params['backup']:
            result['__backup__'] = contents

    if any((module.params['src'], module.params['lines'], replace_src)):
        match = module.params['match']
        replace = module.params['replace']

        commit = not module.check_mode
        candidate = get_candidate(module)
        running = get_running_config(module, contents, flags=flags)
        if replace_src:
            commands = candidate.split('\n')
            result['commands'] = result['updates'] = commands
            if commit:
                load_config(module, commands, replace=replace_src)

            result['changed'] = True
        else:
            try:
                response = connection.get_diff(
                    candidate=candidate,
                    running=running,
                    diff_match=match,
                    diff_ignore_lines=diff_ignore_lines,
                    path=path,
                    diff_replace=replace)
            except ConnectionError as exc:
                module.fail_json(
                    msg=to_text(exc, errors='surrogate_then_replace'))

            config_diff = response['config_diff']
            if config_diff:
                commands = config_diff.split('\n')

                if module.params['before']:
                    commands[:0] = module.params['before']

                if module.params['after']:
                    commands.extend(module.params['after'])

                result['commands'] = commands
                result['updates'] = commands

                if commit:
                    load_config(module, commands, replace=replace_src)

                result['changed'] = True

    running_config = module.params['running_config']
    startup_config = None

    if module.params['save_when'] == 'always':
        save_config(module, result)
    elif module.params['save_when'] == 'modified':
        output = execute_show_commands(
            module, ['show running-config', 'show startup-config'])

        running_config = NetworkConfig(indent=2,
                                       contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(indent=2,
                                       contents=output[1],
                                       ignore_lines=diff_ignore_lines)

        if running_config.sha1 != startup_config.sha1:
            save_config(module, result)
    elif module.params['save_when'] == 'changed' and result['changed']:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = execute_show_commands(module, 'show running-config')
            contents = output[0]
        else:
            contents = running_config

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=2,
                                       contents=contents,
                                       ignore_lines=diff_ignore_lines)

        if module.params['diff_against'] == 'running':
            if module.check_mode:
                module.warn(
                    "unable to perform diff against running-config due to check mode"
                )
                contents = None
            else:
                contents = config.config_text

        elif module.params['diff_against'] == 'startup':
            if not startup_config:
                output = execute_show_commands(module, 'show startup-config')
                contents = output[0]
            else:
                contents = startup_config.config_text

        elif module.params['diff_against'] == 'intended':
            contents = module.params['intended_config']

        if contents is not None:
            base_config = NetworkConfig(indent=2,
                                        contents=contents,
                                        ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                if module.params['diff_against'] == 'intended':
                    before = running_config
                    after = base_config
                elif module.params['diff_against'] in ('startup', 'running'):
                    before = base_config
                    after = running_config

                result.update({
                    'changed': True,
                    'diff': {
                        'before': str(before),
                        'after': str(after)
                    }
                })

    module.exit_json(**result)