def map_config_to_obj(module):
    obj = []
    compare = module.params['check_running_config']
    out = get_config(module, flags='| include ip route', compare=compare)

    for line in out.splitlines():
        splitted_line = line.split()
        if len(splitted_line) not in (4, 5, 6):
            continue
        cidr = ip_network(to_text(splitted_line[2]))
        prefix = str(cidr.network_address)
        mask = str(cidr.netmask)
        next_hop = splitted_line[3]
        if len(splitted_line) == 6:
            admin_distance = splitted_line[5]
        else:
            admin_distance = '1'

        obj.append({
            'prefix': prefix,
            'mask': mask,
            'next_hop': next_hop,
            'admin_distance': admin_distance
        })

    return obj
def map_config_to_obj(module):
    compare = module.params['check_running_config']
    config = get_config(module, flags=['| begin interface'], compare=compare)
    configobj = NetworkConfig(indent=1, contents=config)

    match = re.findall(r'^interface (\S+ \S+)', config, re.M)
    if not match:
        return list()

    instances = list()

    for item in set(match):
        ipv4 = parse_config_argument(configobj, item, 'ip address')
        if ipv4:
            address = ipv4.strip().split(' ')
            if len(address) == 2 and is_netmask(address[1]):
                ipv4 = '{0}/{1}'.format(address[0],
                                        to_text(to_masklen(address[1])))
        obj = {
            'name': item,
            'ipv4': ipv4,
            'ipv6': parse_config_argument(configobj, item, 'ipv6 address'),
            'state': 'present'
        }
        instances.append(obj)

    return instances
def get_running_config(module, current_config=None, flags=None):
    running = module.params['running_config']
    if not running:
        if not module.params['defaults'] and current_config:
            running = current_config
        else:
            running = get_config(module, flags=flags)

    return running
Example #4
0
def map_config_to_obj(module):
    compare = module.params['check_running_config']
    config = get_config(module, None, compare=compare)
    return {
        'hostname': parse_hostname(config),
        'domain_search': parse_domain_search(config),
        'name_servers': parse_name_servers(config),
        'aaa_servers': parse_aaa_servers(config)
    }
Example #5
0
def map_config_to_obj(module):
    compare = module.params.get('check_running_config')
    obj = {
        'banner': module.params['banner'],
        'state': 'absent',
        'enterkey': False
    }
    exec_command(module, 'skip')
    output_text = ''
    output_re = ''
    out = get_config(module,
                     flags=['| begin banner %s' % module.params['banner']],
                     compare=module.params['check_running_config'])
    if out:
        try:
            output_re = re.search(
                r'banner %s( require-enter-key)' % module.params['banner'],
                out, re.S).group(0)
            obj['enterkey'] = True
        except BaseException:
            pass
        try:
            output_text = re.search(
                r'banner %s (\$([^\$])+\$){1}' % module.params['banner'], out,
                re.S).group(1).strip('$\n')
        except BaseException:
            pass

    else:
        output_text = None
    if output_text:
        obj['text'] = output_text
        obj['state'] = 'present'
    if module.params['check_running_config'] is False:
        obj = {
            'banner': module.params['banner'],
            'state': 'absent',
            'enterkey': False,
            'text': 'JUNK'
        }
    return obj
def map_config_to_obj(module):
    objs = dict()
    compare = module.params['check_running_config']
    config = get_config(module, None, compare=compare)
    obj = None
    for line in config.split('\n'):
        l = line.strip()
        match1 = re.search(r'lag (\S+) (\S+) id (\S+)', l, re.M)
        if match1:
            obj = dict()
            obj['name'] = match1.group(1)
            obj['mode'] = match1.group(2)
            obj['group'] = match1.group(3)
            obj['state'] = 'present'
            obj['members'] = list()
        else:
            match2 = re.search(r'ports .*', l, re.M)
            if match2 and obj is not None:
                obj['members'].extend(range_to_members(match2.group(0)))
            elif obj is not None:
                objs[obj['group']] = obj
                obj = None
    return objs
def map_config_to_obj(module):
    compare = module.params['check_running_config']
    data = get_config(module, flags=['| include username'], compare=compare)

    match = re.findall(r'(?:^(?:u|\s{2}u))sername (\S+)', data, re.M)
    if not match:
        return list()

    instances = list()

    for user in set(match):
        regex = r'username %s .+$' % user
        cfg = re.findall(regex, data, re.M)
        cfg = '\n'.join(cfg)
        obj = {
            'name': user,
            'state': 'present',
            'nopassword': '******' in cfg,
            'configured_password': None,
            'privilege': parse_privilege(cfg)
        }
        instances.append(obj)

    return instances
def map_config_to_obj(module):
    config = get_config(module)
    vlans = parse_vlan_id(module)
    instance = list()

    for item in set(vlans):
        obj = {
            'vlan_id':
            item,
            'name':
            parse_name_argument(module, item),
            'interfaces':
            parse_interfaces_argument(module, item, 'interfaces'),
            'tagged':
            parse_interfaces_argument(module, item, 'tagged'),
            'ip_dhcp_snooping':
            parse_config_argument(config,
                                  'ip dhcp snooping vlan {0}'.format(item)),
            'ip_arp_inspection':
            parse_config_argument(config,
                                  'ip arp inspection vlan {0}'.format(item)),
        }
        instance.append(obj)
    return instance
Example #9
0
def map_config_to_obj(module):
    compare = module.params['check_running_config']
    config = get_config(module, None, compare)
    configobj = NetworkConfig(indent=1, contents=config)
    match = re.findall(r'^interface (.+)$', config, re.M)

    if not match:
        return list()

    instances = list()

    for item in set(match):
        obj = {
            'name': item,
            'port-name': parse_config_argument(configobj, item, 'port-name'),
            'speed-duplex': parse_config_argument(configobj, item,
                                                  'speed-duplex'),
            'stp': parse_stp_arguments(module, item),
            'disable': True if parse_enable(configobj, item) else False,
            'power': parse_power_argument(configobj, item),
            'state': 'present'
        }
        instances.append(obj)
    return instances
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        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']),
        multiline_delimiter=dict(default='@'),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified', 'changed'],
                       default='never'),
        diff_against=dict(choices=['startup', 'intended', 'running']),
        diff_ignore_lines=dict(type='list'),
    )

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

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

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

    result = {'changed': False}

    warnings = list()
    check_args(module, warnings)
    result['warnings'] = warnings
    run_commands(module, 'skip')
    diff_ignore_lines = module.params['diff_ignore_lines']
    config = None
    contents = None
    flags = None if module.params['defaults'] else []
    connection = get_connection(module)

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

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

        candidate = get_candidate_config(module)
        running = get_running_config(module, contents, flags=flags)
        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']
        banner_diff = response['banner_diff']

        if config_diff or banner_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
            result['banners'] = banner_diff

            # send the configuration commands to the device and merge
            # them with the current running config
            if not module.check_mode:
                if commands:
                    edit_config_or_macro(connection, commands)
                if banner_diff:
                    connection.edit_banner(candidate=json.dumps(banner_diff),
                                           multiline_delimiter=module.
                                           params['multiline_delimiter'])

            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 = run_commands(module,
                              ['show running-config', 'show configuration'])

        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:
            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 = run_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=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, 'show configuration')
                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:
                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)
def map_config_to_obj(module):
    obj = []
    facility = ''
    addr6 = False
    dest_group = ('host', 'console', 'buffered', 'persistence', 'enable')
    dest_level = ('alerts', 'critical', 'debugging', 'emergencies', 'errors',
                  'informational', 'notifications', 'warnings')
    buff_level = list()
    if module.params['check_running_config'] is False:
        return []
    data = get_config(module, flags=['| include logging'])
    facility_match = re.search(r'^logging facility (\S+)', data, re.M)
    if facility_match:
        facility = facility_match.group(1)
        obj.append({'dest': 'facility', 'facility': facility})
    else:
        obj.append({'dest': 'facility', 'facility': 'user'})
    for line in data.split('\n'):
        match = re.search(r'^logging (\S+)', line.strip(), re.M)
        if match:

            if match.group(1) in dest_group:
                dest = match.group(1)
                if dest == 'host':
                    obj.append({
                        'dest': dest,
                        'name': parse_name(line.strip(), dest),
                        'udp_port': parse_port(line, dest),
                        'level': None,
                        'addr6': parse_address(line, dest)
                    })
                elif dest == 'buffered':
                    obj.append({
                        'dest': dest,
                        'level': None,
                        'name': None,
                        'udp_port': None,
                        'addr6': False
                    })
                else:
                    if dest == 'enable':
                        dest = 'rfc5424'
                    obj.append({
                        'dest': dest,
                        'level': None,
                        'name': None,
                        'udp_port': None,
                        'addr6': False
                    })
        else:

            ip_match = re.search(r'^no logging buffered (\S+)', line, re.M)
            if ip_match:
                dest = 'buffered'
                buff_level.append(ip_match.group(1))
    if 'no logging on' not in data:
        obj.append({
            'dest': 'on',
            'level': None,
            'name': None,
            'udp_port': None,
            'addr6': False
        })
    levels = set()
    for items in dest_level:
        if items not in buff_level:
            levels.add(items)
    obj.append({
        'dest': 'buffered',
        'level': levels,
        'name': None,
        'udp_port': None,
        'addr6': False
    })
    return obj