Ejemplo n.º 1
0
def main():
    """ main entry point for module execution
    """

    argument_spec = dict(src=dict(required=True),
                         force=dict(default=False, type='bool'),
                         include_defaults=dict(default=False, type='bool'),
                         backup=dict(default=False, type='bool'),
                         replace=dict(default=False, type='bool'),
                         config=dict())

    argument_spec.update(eos_local.eapi_argument_spec)

    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

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

    warnings = check_args(module)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    src = module.params['src']
    candidate = NetworkConfig(contents=src, indent=3)

    if module.params['backup']:
        result['__backup__'] = get_config()

    if not module.params['force']:
        contents = get_current_config(module)
        configobj = NetworkConfig(contents=contents, indent=3)
        commands = candidate.difference(configobj)
        commands = dumps(commands, 'commands').split('\n')
        commands = [str(c).strip() for c in commands if c]
    else:
        commands = [c.strip() for c in str(candidate).split('\n')]

    # FIXME not implemented yet!!
    if replace:
        if module.params['transport'] == 'cli':
            module.fail_json(
                msg='config replace is only supported over eos_local')
        commands = str(candidate).split('\n')

    if commands:
        commands = filter_exit(commands)
        commit = not module.check_mode
        load_config(commands, commit=commit)
        result['changed'] = True

    result['updates'] = commands

    module.exit_json(**result)
Ejemplo n.º 2
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(banner=dict(required=True, choices=['login', 'motd']),
                         text=dict(),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

    required_if = [('state', 'present', ('text', ))]

    module = LocalAnsibleModule(argument_spec=argument_spec,
                                required_if=required_if,
                                supports_check_mode=True)

    result = {'changed': False}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 3
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        hostname=dict(),
        domain_name=dict(),
        domain_list=dict(type='list'),

        # { interface: <str>, vrf: <str> }
        lookup_source=dict(type='list'),

        # { server: <str>; vrf: <str> }
        name_servers=dict(type='list'),
        state=dict(default='present', choices=['present', 'absent']))

    module = LocalAnsibleModule(argument_spec=argument_spec,
                                supports_check_mode=True)

    result = {'changed': False}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(want, have, module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 4
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(users=dict(type='list', aliases=['collection']),
                         username=dict(aliases=['name']),
                         password=dict(no_log=True),
                         nopassword=dict(type='bool'),
                         update_password=dict(default='always',
                                              choices=['on_create', 'always']),
                         privilege=dict(type='int'),
                         role=dict(),
                         sshkey=dict(),
                         purge=dict(type='bool', default=False),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

    argument_spec.update(eos_argument_spec)
    mutually_exclusive = [('username', 'users')]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(update_objects(want, have), module)

    if module.params['purge']:
        want_users = [
            x['username'] if 'username' in x else x['name'] for x in want
        ]
        have_users = [x['username'] for x in have]
        for item in set(have_users).difference(want_users):
            if item != 'admin':
                commands.append('no username %s' % item)

    result['commands'] = commands

    # the eos cli prevents this by rule so capture it and display
    # a nice failure message
    if 'no username admin' in commands:
        module.fail_json(msg='cannot delete the `admin` account')

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 5
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        vlan_id=dict(type='int'),
        name=dict(),
        interfaces=dict(type='list'),
        delay=dict(default=10, type='int'),
        state=dict(default='present',
                   choices=['present', 'absent', 'active', 'suspend'])
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['vlan_id'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
        purge=dict(default=False, type='bool')
    )

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)

    required_one_of = [['vlan_id', 'aggregate']]
    mutually_exclusive = [['vlan_id', 'aggregate']]
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_one_of=required_one_of,
                           mutually_exclusive=mutually_exclusive)

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    if result['changed']:
        check_declarative_intent_params(want, module)

    module.exit_json(**result)
Ejemplo n.º 6
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        vlan_id=dict(type='int'),
        name=dict(),
        interfaces=dict(type='list'),
        delay=dict(default=10, type='int'),
        state=dict(default='present',
                   choices=['present', 'absent', 'active', 'suspend']))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['vlan_id'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec),
                         purge=dict(default=False, type='bool'))

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)

    required_one_of = [['vlan_id', 'aggregate']]
    mutually_exclusive = [['vlan_id', 'aggregate']]
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_one_of=required_one_of,
                           mutually_exclusive=mutually_exclusive)

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    if result['changed']:
        check_declarative_intent_params(want, module)

    module.exit_json(**result)
Ejemplo n.º 7
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        http=dict(aliases=['enable_http'], type='bool'),
        http_port=dict(type='int'),

        https=dict(aliases=['enable_https'], type='bool'),
        https_port=dict(type='int'),

        local_http=dict(aliases=['enable_local_http'], type='bool'),
        local_http_port=dict(type='int'),

        socket=dict(aliases=['enable_socket'], type='bool'),

        vrf=dict(default='default'),

        config=dict(),
        state=dict(default='started', choices=['stopped', 'started']),
    )

    argument_spec.update(eos_argument_spec)

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

    check_transport(module)

    result = {'changed': False}

    warnings = list()
    if module.params['config']:
        warnings.append('config parameter is no longer necessary and will be ignored')

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module, warnings)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    if result['changed']:
        verify_state((want, have), module)

    collect_facts(module, result)

    if warnings:
        result['warnings'] = warnings

    module.exit_json(**result)
Ejemplo n.º 8
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        http=dict(aliases=['enable_http'], type='bool'),
        http_port=dict(type='int'),
        https=dict(aliases=['enable_https'], type='bool'),
        https_port=dict(type='int'),
        local_http=dict(aliases=['enable_local_http'], type='bool'),
        local_http_port=dict(type='int'),
        socket=dict(aliases=['enable_socket'], type='bool'),
        vrf=dict(default='default'),
        config=dict(),
        state=dict(default='started', choices=['stopped', 'started']),
    )

    argument_spec.update(eos_argument_spec)

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

    check_transport(module)

    result = {'changed': False}

    warnings = list()
    if module.params['config']:
        warnings.append(
            'config parameter is no longer necessary and will be ignored')

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module, warnings)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    if result['changed']:
        verify_state((want, have), module)

    collect_facts(module, result)

    if warnings:
        result['warnings'] = warnings

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        dest=dict(choices=DEST_GROUP),
        name=dict(),
        size=dict(type='int'),
        facility=dict(),
        level=dict(choices=LEVEL_GROUP),
        state=dict(default='present', choices=['present', 'absent']),
    )

    aggregate_spec = deepcopy(element_spec)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec), )

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)

    required_if = [('dest', 'host', ['name'])]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module, required_if=required_if)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 10
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        dest=dict(choices=DEST_GROUP),
        name=dict(),
        size=dict(type='int'),
        facility=dict(),
        level=dict(choices=LEVEL_GROUP),
        state=dict(default='present', choices=['present', 'absent']),
    )

    aggregate_spec = deepcopy(element_spec)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec),
    )

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)

    required_if = [('dest', 'host', ['name'])]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module, required_if=required_if)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 11
0
def run(module, result):
    match = module.params['match']
    replace = module.params['replace']

    candidate = get_candidate(module)

    if match != 'none' and replace != 'config':
        config_text = get_running_config(module)
        config = NetworkConfig(indent=3, contents=config_text)
        path = module.params['parents']
        configobjs = candidate.difference(config,
                                          match=match,
                                          replace=replace,
                                          path=path)
    else:
        configobjs = candidate.items

    if configobjs:
        commands = dumps(configobjs, 'commands').split('\n')

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

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

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

        replace = module.params['replace'] == 'config'
        commit = not module.check_mode

        response = load_config(module,
                               commands,
                               replace=replace,
                               commit=commit)

        if 'diff' in response:
            result['diff'] = {'prepared': response['diff']}

        if 'session' in response:
            result['session'] = response['session']

        result['changed'] = True
Ejemplo n.º 12
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(name=dict(required=True),
                         interfaces=dict(type='list'),
                         delay=dict(default=10, type='int'),
                         rd=dict(),
                         aggregate=dict(),
                         purge=dict(default=False, type='bool'),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

    argument_spec.update(eos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    if result['changed']:
        check_declarative_intent_params(module)

    module.exit_json(**result)
Ejemplo n.º 13
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        hostname=dict(),

        domain_name=dict(),
        domain_list=dict(type='list', aliases=['domain_search']),

        # { interface: <str>, vrf: <str> }
        lookup_source=dict(type='list'),

        # { server: <str>; vrf: <str> }
        name_servers=dict(type='list'),

        state=dict(default='present', choices=['present', 'absent'])
    )

    argument_spec.update(eos_argument_spec)

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

    result = {'changed': False}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(want, have, module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 14
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        banner=dict(required=True, choices=['login', 'motd']),
        text=dict(),
        state=dict(default='present', choices=['present', 'absent'])
    )

    argument_spec.update(eos_argument_spec)

    required_if = [('state', 'present', ('text',))]

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

    warnings = list()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings
    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 15
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        http=dict(aliases=['enable_http'], type='bool'),
        http_port=dict(type='int'),
        https=dict(aliases=['enable_https'], type='bool'),
        https_port=dict(type='int'),
        local_http=dict(aliases=['enable_local_http'], type='bool'),
        local_http_port=dict(type='int'),
        socket=dict(aliases=['enable_socket'], type='bool'),
        vrf=dict(default='default'),
        state=dict(default='started', choices=['stopped', 'started']),
    )

    module = LocalAnsibleModule(argument_spec=argument_spec,
                                supports_check_mode=True)

    result = {'changed': False}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    collect_facts(module, result)

    module.exit_json(**result)
Ejemplo n.º 16
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),
        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']),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified'],
                       default='never'),
        diff_against=dict(
            choices=['startup', 'session', 'intended', 'running'],
            default='session'),
        diff_ignore_lines=dict(type='list'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),

        # save is deprecated as of ans2.4, use save_when instead
        save=dict(default=False, type='bool', removed_in_version='2.4'),

        # force argument deprecated in ans2.2
        force=dict(default=False, type='bool', removed_in_version='2.2'))

    argument_spec.update(eos_argument_spec)

    mutually_exclusive = [('lines', 'src'), ('save', 'save_when')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['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()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    config = None

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

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

        candidate = get_candidate(module)

        if match != 'none' and replace != 'config':
            config_text = get_running_config(module)
            config = NetworkConfig(indent=3, contents=config_text)
            path = module.params['parents']
            configobjs = candidate.difference(config,
                                              match=match,
                                              replace=replace,
                                              path=path)
        else:
            configobjs = candidate.items

        if configobjs:
            commands = dumps(configobjs, 'commands').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

            replace = module.params['replace'] == 'config'
            commit = not module.check_mode

            response = load_config(module,
                                   commands,
                                   replace=replace,
                                   commit=commit)

            if 'diff' in response and module.params[
                    'diff_against'] == 'session':
                result['diff'] = {'prepared': response['diff']}

            if 'session' in response:
                result['session'] = response['session']

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

    if module.params['save_when'] != 'never':
        output = run_commands(module, [{
            'command': 'show running-config',
            'output': 'text'
        }, {
            'command': 'show startup-config',
            'output': 'text'
        }])

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

        if running_config.sha1 != startup_config.sha1 or module.params[
                'save_when'] == 'always':
            result['changed'] = True
            if not module.check_mode:
                cmd = {
                    'command': 'copy running-config startup-config',
                    'output': 'text'
                }
                run_commands(module, [cmd])
            else:
                module.warn(
                    'Skipping command `copy running-config startup-config` '
                    'due to check_mode.  Configuration not copied to '
                    'non-volatile storage')

    if module._diff:
        if not running_config:
            output = run_commands(module, {
                'command': 'show running-config',
                'output': 'text'
            })
            contents = output[0]
        else:
            contents = running_config.config_text

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=1,
                                       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 = run_commands(module, {
                    'command': 'show startup-config',
                    'output': 'text'
                })
                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=1,
                                        contents=contents,
                                        ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                result.update({
                    'changed': True,
                    'diff': {
                        'before': str(base_config),
                        'after': str(running_config)
                    }
                })

    module.exit_json(**result)
Ejemplo n.º 17
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),

        configured_password=dict(no_log=True),
        nopassword=dict(type='bool'),
        update_password=dict(default='always', choices=['on_create', 'always']),

        privilege=dict(type='int'),
        role=dict(),

        sshkey=dict(),

        state=dict(default='present', choices=['present', 'absent'])
    )

    aggregate_spec = deepcopy(element_spec)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type='list', elements='dict', options=aggregate_spec, aliases=['collection', 'users']),
        purge=dict(type='bool', default=False)
    )

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)
    mutually_exclusive = [('name', 'aggregate')]

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

    warnings = list()
    if module.params['password'] and not module.params['configured_password']:
        warnings.append(
            'The "password" argument is used to authenticate the current connection. ' +
            'To set a user password use "configured_password" instead.'
        )

    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(update_objects(want, have), module)

    if module.params['purge']:
        want_users = [x['name'] for x in want]
        have_users = [x['name'] for x in have]
        for item in set(have_users).difference(want_users):
            if item != 'admin':
                commands.append('no username %s' % item)

    result['commands'] = commands

    # the eos cli prevents this by rule so capture it and display
    # a nice failure message
    if 'no username admin' in commands:
        module.fail_json(msg='cannot delete the `admin` account')

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 18
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(address=dict(type='str', aliases=['prefix']),
                        next_hop=dict(type='str'),
                        admin_distance=dict(default=1, type='int'),
                        state=dict(default='present',
                                   choices=['present', 'absent']))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['address'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec), )

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)

    required_one_of = [['aggregate', 'address']]
    required_together = [['address', 'next_hop']]
    mutually_exclusive = [['aggregate', 'address']]

    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=required_one_of,
                           required_together=required_together,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    address = module.params['address']
    prefix = address.split('/')[-1]
    warnings = list()
    check_args(module, warnings)

    if '/' not in address or not validate_ip_address(address.split('/')[0]):
        module.fail_json(msg='{} is not a valid IP address'.format(address))

    if not validate_prefix(prefix):
        module.fail_json(
            msg='Length of prefix should be between 0 and 32 bits')

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)
    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Ejemplo n.º 19
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),

        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']),

        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),

        save_when=dict(choices=['always', 'never', 'modified'], default='never'),

        diff_against=dict(choices=['startup', 'session', 'intended', 'running'], default='session'),
        diff_ignore_lines=dict(type='list'),

        running_config=dict(aliases=['config']),
        intended_config=dict(),

        # save is deprecated as of ans2.4, use save_when instead
        save=dict(default=False, type='bool', removed_in_version='2.4'),

        # force argument deprecated in ans2.2
        force=dict(default=False, type='bool', removed_in_version='2.2')
    )

    argument_spec.update(eos_argument_spec)

    mutually_exclusive = [('lines', 'src'),
                          ('save', 'save_when')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['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()
    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    config = None

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

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

        candidate = get_candidate(module)

        if match != 'none' and replace != 'config':
            config_text = get_running_config(module)
            config = NetworkConfig(indent=3, contents=config_text)
            path = module.params['parents']
            configobjs = candidate.difference(config, match=match, replace=replace, path=path)
        else:
            configobjs = candidate.items

        if configobjs:
            commands = dumps(configobjs, 'commands').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

            replace = module.params['replace'] == 'config'
            commit = not module.check_mode

            response = load_config(module, commands, replace=replace, commit=commit)

            if 'diff' in response and module.params['diff_against'] == 'session':
                result['diff'] = {'prepared': response['diff']}

            if 'session' in response:
                result['session'] = response['session']

            result['changed'] = True


    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

    if module.params['save_when'] != 'never':
        output = run_commands(module, [{'command': 'show running-config', 'output': 'text'},
                                       {'command': 'show startup-config', 'output': 'text'}])

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

        if running_config.sha1 != startup_config.sha1 or module.params['save_when'] == 'always':
            result['changed'] = True
            if not module.check_mode:
                cmd = {'command': 'copy running-config startup-config', 'output': 'text'}
                run_commands(module, [cmd])
            else:
                module.warn('Skipping command `copy running-config startup-config` '
                            'due to check_mode.  Configuration not copied to '
                            'non-volatile storage')

    if module._diff:
        if not running_config:
            output = run_commands(module, {'command': 'show running-config', 'output': 'text'})
            contents = output[0]
        else:
            contents = running_config.config_text

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=1, 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 = run_commands(module, {'command': 'show startup-config', 'output': 'text'})
                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=1, contents=contents, ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                result.update({
                    'changed': True,
                    'diff': {'before': str(base_config), 'after': str(running_config)}
                })

    module.exit_json(**result)