Beispiel #1
0
def config_to_dict(module):
    data = get_config(module)
    obj = []

    for line in data.split('\n'):
        if line.startswith('set system syslog'):
            match = re.search(r'set system syslog (\S+)', line, re.M)
            dest = match.group(1)
            if dest == 'host':
                match = re.search(r'host (\S+)', line, re.M)
                name = match.group(1)
            elif dest == 'file':
                match = re.search(r'file (\S+)', line, re.M)
                name = match.group(1)
            elif dest == 'user':
                match = re.search(r'user (\S+)', line, re.M)
                name = match.group(1)
            else:
                name = None

            if 'facility' in line:
                match = re.search(r'facility (\S+)', line, re.M)
                facility = match.group(1)
            if 'level' in line:
                match = re.search(r'level (\S+)', line, re.M)
                level = match.group(1).strip("'")

                obj.append({
                    'dest': dest,
                    'name': name,
                    'facility': facility,
                    'level': level
                })

    return obj
Beispiel #2
0
def config_to_dict(module):
    data = get_config(module)
    obj = []

    for line in data.split('\n'):
        if line.startswith('set protocols static route'):
            match = re.search(r'static route (\S+)', line, re.M)
            prefix = match.group(1).split('/')[0]
            mask = match.group(1).split('/')[1]
            if 'next-hop' in line:
                match_hop = re.search(r'next-hop (\S+)', line, re.M)
                next_hop = match_hop.group(1).strip("'")

                match_distance = re.search(r'distance (\S+)', line, re.M)
                if match_distance is not None:
                    admin_distance = match_distance.group(1)[1:-1]
                else:
                    admin_distance = None

                if admin_distance is not None:
                    obj.append({
                        'prefix': prefix,
                        'mask': mask,
                        'next_hop': next_hop,
                        'admin_distance': admin_distance
                    })
                else:
                    obj.append({
                        'prefix': prefix,
                        'mask': mask,
                        'next_hop': next_hop,
                        'admin_distance': 'None'
                    })

    return obj
def has_lldp(module):
    config = get_config(module).splitlines()

    if "set service 'lldp'" in config or 'set service lldp' in config:
        return True
    else:
        return False
def config_to_dict(module):
    data = get_config(module)
    output = None
    obj = {'banner': module.params['banner'], 'state': 'absent'}

    for line in data.split('\n'):
        if line.startswith('set system login banner %s' % obj['banner']):
            match = re.findall(r'%s (.*)' % obj['banner'], line, re.M)
            output = match
    if output:
        obj['text'] = output[0].encode().decode('unicode_escape')
        obj['state'] = 'present'

    return obj
Beispiel #5
0
def config_to_dict(module):
    data = get_config(module)

    config = {'domain_search': [], 'name_server': []}

    for line in data.split('\n'):
        if line.startswith('set system host-name'):
            config['host_name'] = line[22:-1]
        elif line.startswith('set system domain-name'):
            config['domain_name'] = line[24:-1]
        elif line.startswith('set system domain-search domain'):
            config['domain_search'].append(line[33:-1])
        elif line.startswith('set system name-server'):
            config['name_server'].append(line[24:-1])

    return config
def map_config_to_obj(module):
    data = get_config(module, flags=['| grep interface'])
    obj = []
    for line in data.split('\n'):
        if line.startswith('set interfaces ethernet'):
            match = re.search(r'set interfaces ethernet (\S+)', line, re.M)
            name = match.group(1)
            if name:
                interface = {}
                for item in obj:
                    if item['name'] == name:
                        interface = item
                        break

                if not interface:
                    interface = {'name': name}
                    obj.append(interface)

                match = re.search(r'%s (\S+)' % name, line, re.M)
                if match:
                    param = match.group(1)
                    if param == 'description':
                        match = re.search(r'description (.+)', line, re.M)
                        description = match.group(1).strip("'")
                        interface['description'] = description
                    elif param == 'speed':
                        match = re.search(r'speed (\S+)', line, re.M)
                        speed = match.group(1).strip("'")
                        interface['speed'] = speed
                    elif param == 'mtu':
                        match = re.search(r'mtu (\S+)', line, re.M)
                        mtu = match.group(1).strip("'")
                        interface['mtu'] = int(mtu)
                    elif param == 'duplex':
                        match = re.search(r'duplex (\S+)', line, re.M)
                        duplex = match.group(1).strip("'")
                        interface['duplex'] = duplex
                    elif param.strip("'") == 'disable':
                        interface['disable'] = True

    return obj
def map_config_to_obj(module):
    obj = []
    config = get_config(module).splitlines()

    output = [c for c in config if c.startswith("set service lldp interface")]

    for i in output:
        splitted_line = i.split()

        if len(splitted_line) > 5:
            new_obj = {'name': splitted_line[4]}

            if splitted_line[5] == "'disable'":
                new_obj['state'] = 'disabled'
        else:
            new_obj = {'name': splitted_line[4][1:-1]}
            new_obj['state'] = 'present'

        obj.append(new_obj)

    return obj
Beispiel #8
0
def main():
    backup_spec = dict(filename=dict(), dir_path=dict(type='path'))
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(type='list'),
        match=dict(default='line', choices=['line', 'none']),
        comment=dict(default=DEFAULT_COMMENT),
        config=dict(),
        backup=dict(type='bool', default=False),
        backup_options=dict(type='dict', options=backup_spec),
        save=dict(type='bool', default=False),
    )

    argument_spec.update(vyos_argument_spec)

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

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

    warnings = list()

    result = dict(changed=False, warnings=warnings)

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

    if any((module.params['src'], module.params['lines'])):
        run(module, result)

    if module.params['save']:
        diff = run_commands(module, commands=['configure', 'compare saved'])[1]
        if diff != '[edit]':
            run_commands(module, commands=['save'])
            result['changed'] = True
        run_commands(module, commands=['exit'])

    module.exit_json(**result)
Beispiel #9
0
def config_to_dict(module):
    data = get_config(module)

    match = re.findall(r'^set system login user (\S+)', data, re.M)
    if not match:
        return list()

    instances = list()

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

    return instances
Beispiel #10
0
def run(module, result):
    # get the current active config from the node or passed in via
    # the config param
    config = module.params['config'] or get_config(module)

    # create the candidate config object from the arguments
    candidate = get_candidate(module)

    # create loadable config that includes only the configuration updates
    connection = get_connection(module)
    try:
        response = connection.get_diff(candidate=candidate,
                                       running=config,
                                       diff_match=module.params['match'])
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

    commands = response.get('config_diff')
    sanitize_config(commands, result)

    result['commands'] = commands

    commit = not module.check_mode
    comment = module.params['comment']

    diff = None
    if commands:
        diff = load_config(module, commands, commit=commit, comment=comment)

        if result.get('filtered'):
            result['warnings'].append('Some configuration commands were '
                                      'removed, please see the filtered key')

        result['changed'] = True

    if module._diff:
        result['diff'] = {'prepared': diff}