def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    interface_exist = check_interface(module, netcfg)
    if interface_exist:
        parents = ['interface {0}'.format(interface_exist)]
        temp_config = netcfg.get_section(parents)

        if 'member vni {0} associate-vrf'.format(module.params['vni']) in temp_config:
            parents.append('member vni {0} associate-vrf'.format(module.params['vni']))
            config = netcfg.get_section(parents)
        elif "member vni {0}".format(module.params['vni']) in temp_config:
            parents.append('member vni {0}'.format(module.params['vni']))
            config = netcfg.get_section(parents)
        else:
            config = {}

        if config:
            for arg in args:
                if arg not in ['interface', 'vni']:
                    existing[arg] = get_value(arg, config, module)
            existing['interface'] = interface_exist
            existing['vni'] = module.params['vni']

    return existing, interface_exist
示例#2
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    interface_exist = check_interface(module, netcfg)
    if interface_exist:
        parents = ['interface {0}'.format(interface_exist)]
        temp_config = netcfg.get_section(parents)

        if 'member vni {0} associate-vrf'.format(
                module.params['vni']) in temp_config:
            parents.append('member vni {0} associate-vrf'.format(
                module.params['vni']))
            config = netcfg.get_section(parents)
        elif "member vni {0}".format(module.params['vni']) in temp_config:
            parents.append('member vni {0}'.format(module.params['vni']))
            config = netcfg.get_section(parents)
        else:
            config = {}

        if config:
            for arg in args:
                if arg not in ['interface', 'vni']:
                    existing[arg] = get_value(arg, config, module)
            existing['interface'] = interface_exist
            existing['vni'] = module.params['vni']

    return existing, interface_exist
示例#3
0
def reconcile_candidate(module, candidate, prefix):
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    state = module.params['state']

    set_command = set_route_command(module, prefix)
    remove_command = remove_route_command(module, prefix)

    parents = []
    commands = []
    if module.params['vrf'] == 'default':
        config = netcfg.get_section(set_command)
        if config and state == 'absent':
            commands = [remove_command]
        elif not config and state == 'present':
            commands = [set_command]
    else:
        parents = ['vrf context {0}'.format(module.params['vrf'])]
        config = netcfg.get_section(parents)
        if not isinstance(config, list):
            config = config.split('\n')
        config = [line.strip() for line in config]
        if set_command in config and state == 'absent':
            commands = [remove_command]
        elif set_command not in config and state == 'present':
            commands = [set_command]

    if commands:
        candidate.add(commands, parents=parents)
示例#4
0
def get_existing(module, prefix, warnings):
    key_map = ['tag', 'pref', 'route_name', 'next_hop']
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = 'vrf context {0}'.format(module.params['vrf'])
    prefix_to_regex = fix_prefix_to_regex(prefix)

    route_regex = r'.*ip\sroute\s{0}\s(?P<next_hop>\S+)(\sname\s(?P<route_name>\S+))?(\stag\s(?P<tag>\d+))?(\s(?P<pref>\d+))?.*'.format(
        prefix_to_regex)

    if module.params['vrf'] == 'default':
        config = str(netcfg)
    else:
        config = netcfg.get_section(parents)

    if config:
        try:
            match_route = re.match(route_regex, config, re.DOTALL)
            group_route = match_route.groupdict()

            for key in key_map:
                if key not in group_route:
                    group_route[key] = ''
            group_route['prefix'] = prefix
            group_route['vrf'] = module.params['vrf']
        except (AttributeError, TypeError):
            group_route = {}
    else:
        group_route = {}
        msg = ("VRF {0} didn't exist.".format(module.params['vrf']))
        if msg not in warnings:
            warnings.append(msg)

    return group_route
示例#5
0
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    asn_regex = re.compile(r'.*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*',
                           re.S)
    match_asn = asn_regex.match(str(netcfg))

    if match_asn:
        existing_asn = match_asn.group('existing_asn')
        parents = ["router bgp {0}".format(existing_asn)]

        if module.params['vrf'] != 'default':
            parents.append('vrf {0}'.format(module.params['vrf']))

        parents.append('neighbor {0}'.format(module.params['neighbor']))
        config = netcfg.get_section(parents)
        if config:
            for arg in args:
                if arg not in ['asn', 'vrf', 'neighbor']:
                    existing[arg] = get_value(arg, config)

            existing['asn'] = existing_asn
            existing['neighbor'] = module.params['neighbor']
            existing['vrf'] = module.params['vrf']
    else:
        warnings.append("The BGP process didn't exist but the task"
                        " just created it.")
    return existing
示例#6
0
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    asn_regex = re.compile(r".*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*",
                           re.S)
    match_asn = asn_regex.match(str(netcfg))

    if match_asn:
        existing_asn = match_asn.group("existing_asn")
        parents = ["router bgp {0}".format(existing_asn)]

        if module.params["vrf"] != "default":
            parents.append("vrf {0}".format(module.params["vrf"]))

        parents.append("neighbor {0}".format(module.params["neighbor"]))
        parents.append("address-family {0} {1}".format(module.params["afi"],
                                                       module.params["safi"]))
        config = netcfg.get_section(parents)

        if config:
            for arg in args:
                if arg not in ["asn", "vrf", "neighbor", "afi", "safi"]:
                    existing[arg] = get_value(arg, config, module)

            existing["asn"] = existing_asn
            existing["neighbor"] = module.params["neighbor"]
            existing["vrf"] = module.params["vrf"]
            existing["afi"] = module.params["afi"]
            existing["safi"] = module.params["safi"]
    else:
        warnings.append(
            "The BGP process didn't exist but the task just created it.")

    return existing
示例#7
0
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module, flags=['bgp all']))

    asn_re = re.compile(r'.*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*', re.S)
    asn_match = asn_re.match(str(netcfg))

    if asn_match:
        existing_asn = asn_match.group('existing_asn')
        bgp_parent = 'router bgp {0}'.format(existing_asn)

        if module.params['vrf'] != 'default':
            parents = [bgp_parent, 'vrf {0}'.format(module.params['vrf'])]
        else:
            parents = [bgp_parent]

        config = netcfg.get_section(parents)
        if config:
            for arg in args:
                if arg != 'asn' and (module.params['vrf'] == 'default' or
                                     arg not in GLOBAL_PARAMS):
                    existing[arg] = get_value(arg, config)

            existing['asn'] = existing_asn
            if module.params['vrf'] == 'default':
                existing['vrf'] = 'default'

    if not existing and module.params['vrf'] != 'default' and module.params['state'] == 'present':
        msg = ("VRF {0} doesn't exist.".format(module.params['vrf']))
        warnings.append(msg)

    return existing
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    asn_regex = re.compile(r'.*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*', re.S)
    match_asn = asn_regex.match(str(netcfg))

    if match_asn:
        existing_asn = match_asn.group('existing_asn')
        parents = ["router bgp {0}".format(existing_asn)]

        if module.params['vrf'] != 'default':
            parents.append('vrf {0}'.format(module.params['vrf']))

        parents.append('neighbor {0}'.format(module.params['neighbor']))
        parents.append('address-family {0} {1}'.format(module.params['afi'], module.params['safi']))
        config = netcfg.get_section(parents)

        if config:
            for arg in args:
                if arg not in ['asn', 'vrf', 'neighbor', 'afi', 'safi']:
                    existing[arg] = get_value(arg, config, module)

            existing['asn'] = existing_asn
            existing['neighbor'] = module.params['neighbor']
            existing['vrf'] = module.params['vrf']
            existing['afi'] = module.params['afi']
            existing['safi'] = module.params['safi']
    else:
        warnings.append("The BGP process didn't exist but the task just created it.")

    return existing
示例#9
0
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module, flags=['bgp all']))

    asn_re = re.compile(r'.*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*', re.S)
    asn_match = asn_re.match(str(netcfg))

    if asn_match:
        existing_asn = asn_match.group('existing_asn')
        bgp_parent = 'router bgp {0}'.format(existing_asn)

        if module.params['vrf'] != 'default':
            parents = [bgp_parent, 'vrf {0}'.format(module.params['vrf'])]
        else:
            parents = [bgp_parent]

        config = netcfg.get_section(parents)
        if config:
            for arg in args:
                if arg != 'asn' and (module.params['vrf'] == 'default' or
                                     arg not in GLOBAL_PARAMS):
                    existing[arg] = get_value(arg, config)

            existing['asn'] = existing_asn
            if module.params['vrf'] == 'default':
                existing['vrf'] = 'default'

    if not existing and module.params['vrf'] != 'default' and module.params['state'] == 'present':
        msg = ("VRF {0} doesn't exist.".format(module.params['vrf']))
        warnings.append(msg)

    return existing
示例#10
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ['router ospf {0}'.format(module.params['ospf'])]

    if module.params['vrf'] != 'default':
        parents.append('vrf {0}'.format(module.params['vrf']))

    config = netcfg.get_section(parents)
    if config:
        if module.params['vrf'] == 'default':
            splitted_config = config.splitlines()
            vrf_index = False
            for index in range(0, len(splitted_config) - 1):
                if 'vrf' in splitted_config[index].strip():
                    vrf_index = index
                    break
            if vrf_index:
                config = '\n'.join(splitted_config[0:vrf_index])

        for arg in args:
            if arg not in ['ospf', 'vrf']:
                existing[arg] = get_value(arg, config, module)

        existing['vrf'] = module.params['vrf']
        existing['ospf'] = module.params['ospf']

    return existing
示例#11
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ['router ospf {0}'.format(module.params['ospf'])]

    if module.params['vrf'] != 'default':
        parents.append('vrf {0}'.format(module.params['vrf']))

    config = netcfg.get_section(parents)
    for arg in args:
        if arg not in ['ospf', 'vrf']:
            existing[arg] = PARAM_TO_DEFAULT_KEYMAP.get(arg)

    if config:
        if module.params['vrf'] == 'default':
            splitted_config = config.splitlines()
            vrf_index = False
            for index in range(0, len(splitted_config) - 1):
                if 'vrf' in splitted_config[index].strip():
                    vrf_index = index
                    break
            if vrf_index:
                config = '\n'.join(splitted_config[0:vrf_index])

        splitted_config = config.splitlines()
        for line in splitted_config:
            if 'passive' in line:
                existing['passive_interface'] = True
            elif 'router-id' in line:
                existing['router_id'] = re.search(r'router-id (\S+)', line).group(1)
            elif 'metric' in line:
                existing['default_metric'] = re.search(r'default-metric (\S+)', line).group(1)
            elif 'adjacency' in line:
                log = re.search(r'log-adjacency-changes(?: (\S+))?', line).group(1)
                if log:
                    existing['log_adjacency'] = log
                else:
                    existing['log_adjacency'] = 'log'
            elif 'auto' in line:
                cost = re.search(r'auto-cost reference-bandwidth (\d+) (\S+)', line).group(1)
                if 'Gbps' in line:
                    cost = int(cost) * 1000
                existing['auto_cost'] = str(cost)
            elif 'bfd' in line:
                existing['bfd'] = 'enable'
            elif 'timers throttle lsa' in line:
                tmp = re.search(r'timers throttle lsa (\S+) (\S+) (\S+)', line)
                existing['timer_throttle_lsa_start'] = tmp.group(1)
                existing['timer_throttle_lsa_hold'] = tmp.group(2)
                existing['timer_throttle_lsa_max'] = tmp.group(3)
            elif 'timers throttle spf' in line:
                tmp = re.search(r'timers throttle spf (\S+) (\S+) (\S+)', line)
                existing['timer_throttle_spf_start'] = tmp.group(1)
                existing['timer_throttle_spf_hold'] = tmp.group(2)
                existing['timer_throttle_spf_max'] = tmp.group(3)
        existing['vrf'] = module.params['vrf']
        existing['ospf'] = module.params['ospf']

    return existing
示例#12
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ['router ospf {0}'.format(module.params['ospf'])]

    if module.params['vrf'] != 'default':
        parents.append('vrf {0}'.format(module.params['vrf']))

    config = netcfg.get_section(parents)
    for arg in args:
        if arg not in ['ospf', 'vrf']:
            existing[arg] = PARAM_TO_DEFAULT_KEYMAP.get(arg)

    if config:
        if module.params['vrf'] == 'default':
            splitted_config = config.splitlines()
            vrf_index = False
            for index in range(0, len(splitted_config) - 1):
                if 'vrf' in splitted_config[index].strip():
                    vrf_index = index
                    break
            if vrf_index:
                config = '\n'.join(splitted_config[0:vrf_index])

        splitted_config = config.splitlines()
        for line in splitted_config:
            if 'passive' in line:
                existing['passive_interface'] = True
            elif 'router-id' in line:
                existing['router_id'] = re.search(r'router-id (\S+)', line).group(1)
            elif 'metric' in line:
                existing['default_metric'] = re.search(r'default-metric (\S+)', line).group(1)
            elif 'adjacency' in line:
                log = re.search(r'log-adjacency-changes(?: (\S+))?', line).group(1)
                if log:
                    existing['log_adjacency'] = log
                else:
                    existing['log_adjacency'] = 'log'
            elif 'auto' in line:
                cost = re.search(r'auto-cost reference-bandwidth (\d+) (\S+)', line).group(1)
                if 'Gbps' in line:
                    cost *= 1000
                existing['auto_cost'] = str(cost)
            elif 'timers throttle lsa' in line:
                tmp = re.search(r'timers throttle lsa (\S+) (\S+) (\S+)', line)
                existing['timer_throttle_lsa_start'] = tmp.group(1)
                existing['timer_throttle_lsa_hold'] = tmp.group(2)
                existing['timer_throttle_lsa_max'] = tmp.group(3)
            elif 'timers throttle spf' in line:
                tmp = re.search(r'timers throttle spf (\S+) (\S+) (\S+)', line)
                existing['timer_throttle_spf_start'] = tmp.group(1)
                existing['timer_throttle_spf_hold'] = tmp.group(2)
                existing['timer_throttle_spf_max'] = tmp.group(3)
        existing['vrf'] = module.params['vrf']
        existing['ospf'] = module.params['ospf']

    return existing
示例#13
0
def has_lldp(module):
    config = get_config(module)
    netcfg = CustomNetworkConfig(indent=1, contents=config)
    parents = [PROTOCOL]
    body = netcfg.get_section(parents)

    for line in body.split('\n'):
        l = line.strip()
        match = re.search(r'disable', l, re.M)
        if match:
            return False

    return True
示例#14
0
def parse_mode(module, config, group, member):
    mode = None
    netcfg = CustomNetworkConfig(indent=1, contents=config)
    parents = ['interface {0}'.format(member)]
    body = netcfg.get_section(parents)

    match_int = re.findall(r'interface {0}\n'.format(member), body, re.M)
    if match_int:
        match = re.search(r'channel-group {0} mode (\S+)'.format(group), body, re.M)
        if match:
            mode = match.group(1)

    return mode
示例#15
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    interface_exist = check_interface(module, netcfg)
    if interface_exist:
        parents = ['interface port-channel{0}'.format(module.params['group'])]
        config = netcfg.get_section(parents)

        if config:
            existing['min_links'] = get_value('min_links', config, module)
            existing.update(get_portchannel(module, netcfg=netcfg))

    return existing, interface_exist
示例#16
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    interface_exist = check_interface(module, netcfg)
    if interface_exist:
        parents = ['interface port-channel{0}'.format(module.params['group'])]
        config = netcfg.get_section(parents)

        if config:
            existing['min_links'] = get_value('min_links', config, module)
            existing.update(get_portchannel(module, netcfg=netcfg))

    return existing, interface_exist
示例#17
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    if module.params['interface'].startswith('loopback') or module.params['interface'].startswith('port-channel'):
        parents = ['interface {0}'.format(module.params['interface'])]
    else:
        parents = ['interface {0}'.format(module.params['interface'].capitalize())]
    config = netcfg.get_section(parents)
    if 'ospf' in config:
        for arg in args:
            if arg not in ['interface']:
                existing[arg] = get_value(arg, config, module)
        existing['interface'] = module.params['interface']
    return existing
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    if module.params['interface'].startswith('loopback') or module.params['interface'].startswith('port-channel'):
        parents = ['interface {0}'.format(module.params['interface'])]
    else:
        parents = ['interface {0}'.format(module.params['interface'].capitalize())]
    config = netcfg.get_section(parents)
    if 'ospf' in config:
        for arg in args:
            if arg not in ['interface']:
                existing[arg] = get_value(arg, config, module)
        existing['interface'] = module.params['interface']
    return existing
def get_existing(module):
    existing = []
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    if module.params['mode'] == 'maintenance':
        parents = ['configure maintenance profile maintenance-mode']
    else:
        parents = ['configure maintenance profile normal-mode']

    config = netcfg.get_section(parents)
    if config:
        existing = config.splitlines()
        existing = [cmd.strip() for cmd in existing]
        existing.pop(0)

    return existing
示例#20
0
def get_existing(module):
    existing = []
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    if module.params['mode'] == 'maintenance':
        parents = ['configure maintenance profile maintenance-mode']
    else:
        parents = ['configure maintenance profile normal-mode']

    config = netcfg.get_section(parents)
    if config:
        existing = config.splitlines()
        existing = [cmd.strip() for cmd in existing]
        existing.pop(0)

    return existing
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    if module.params["interface"].startswith("loopback") or module.params[
        "interface"
    ].startswith("port-channel"):
        parents = ["interface {0}".format(module.params["interface"])]
    else:
        parents = [
            "interface {0}".format(module.params["interface"].capitalize())
        ]
    config = netcfg.get_section(parents)
    if "ospf" in config:
        for arg in args:
            if arg not in ["interface"]:
                existing[arg] = get_value(arg, config, module)
        existing["interface"] = module.params["interface"]
    return existing
示例#22
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module, flags=['all']))

    interface_string = 'interface {0}'.format(module.params['interface'].lower())
    parents = [interface_string]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            existing[arg] = get_value(arg, config, module)

        existing['interface'] = module.params['interface'].lower()
    else:
        if interface_string in str(netcfg):
            existing['interface'] = module.params['interface'].lower()
            for arg in args:
                existing[arg] = ''
    return existing
示例#23
0
def reconcile_candidate(module, candidate, prefix, w):
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    state = w['state']

    set_command = set_route_command(prefix, w)
    remove_command = remove_route_command(prefix, w)

    parents = []
    commands = []
    yrc = remove_command.replace('no ', '')
    if w['vrf'] == 'default':
        netcfg = str(netcfg).split('\n')
        ncfg = []
        for line in netcfg:
            # remove ip route commands of non-default vrfs from
            # the running config just in case the same commands
            # exist in default and non-default vrfs
            if '  ip route' not in line:
                ncfg.append(line)
        if any(yrc in s for s in ncfg) and state == 'absent':
            commands = [remove_command]
        elif set_command not in ncfg and state == 'present':
            if any(yrc in s for s in ncfg):
                commands = [remove_command, set_command]
            else:
                commands = [set_command]
    else:
        parents = ['vrf context {0}'.format(w['vrf'])]
        config = netcfg.get_section(parents)
        if not isinstance(config, list):
            config = config.split('\n')
        config = [line.strip() for line in config]
        if any(yrc in s for s in config) and state == 'absent':
            commands = [remove_command]
        elif set_command not in config and state == 'present':
            if any(yrc in s for s in config):
                commands = [remove_command, set_command]
            else:
                commands = [set_command]

    if commands:
        candidate.add(commands, parents=parents)
示例#24
0
def reconcile_candidate(module, candidate, prefix, w):
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    state = w['state']

    set_command = set_route_command(prefix, w)
    remove_command = remove_route_command(prefix, w)

    parents = []
    commands = []
    yrc = remove_command.replace('no ', '')
    if w['vrf'] == 'default':
        netcfg = str(netcfg).split('\n')
        ncfg = []
        for line in netcfg:
            # remove ip route commands of non-default vrfs from
            # the running config just in case the same commands
            # exist in default and non-default vrfs
            if '  ip route' not in line:
                ncfg.append(line)
        if any(yrc in s for s in ncfg) and state == 'absent':
            commands = [remove_command]
        elif set_command not in ncfg and state == 'present':
            if any(yrc in s for s in ncfg):
                commands = [remove_command, set_command]
            else:
                commands = [set_command]
    else:
        parents = ['vrf context {0}'.format(w['vrf'])]
        config = netcfg.get_section(parents)
        if not isinstance(config, list):
            config = config.split('\n')
        config = [line.strip() for line in config]
        if any(yrc in s for s in config) and state == 'absent':
            commands = [remove_command]
        elif set_command not in config and state == 'present':
            if any(yrc in s for s in config):
                commands = [remove_command, set_command]
            else:
                commands = [set_command]

    if commands:
        candidate.add(commands, parents=parents)
示例#25
0
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    asn_regex = re.compile(r".*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*",
                           re.DOTALL)
    match_asn = asn_regex.match(str(netcfg))

    if match_asn:
        existing_asn = match_asn.group("existing_asn")
        parents = ["router bgp {0}".format(existing_asn)]
        if module.params["vrf"] != "default":
            parents.append("vrf {0}".format(module.params["vrf"]))

        parents.append("address-family {0} {1}".format(module.params["afi"],
                                                       module.params["safi"]))
        config = netcfg.get_section(parents)

        if config:
            for arg in args:
                if arg not in ["asn", "afi", "safi", "vrf"]:
                    gv = get_value(arg, config, module)
                    if gv:
                        existing[arg] = gv
                    else:
                        if (arg != "client_to_client"
                                and arg in PARAM_TO_DEFAULT_KEYMAP.keys()):
                            existing[arg] = PARAM_TO_DEFAULT_KEYMAP.get(arg)
                        else:
                            existing[arg] = gv

            existing["asn"] = existing_asn
            existing["afi"] = module.params["afi"]
            existing["safi"] = module.params["safi"]
            existing["vrf"] = module.params["vrf"]
    else:
        warnings.append(
            "The BGP process {0} didn't exist but the task just created it.".
            format(module.params["asn"]))

    return existing
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    asn_regex = re.compile(r'.*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*',
                           re.DOTALL)
    match_asn = asn_regex.match(str(netcfg))

    if match_asn:
        existing_asn = match_asn.group('existing_asn')
        parents = ["router bgp {0}".format(existing_asn)]
        if module.params['vrf'] != 'default':
            parents.append('vrf {0}'.format(module.params['vrf']))

        parents.append('address-family {0} {1}'.format(module.params['afi'],
                                                       module.params['safi']))
        config = netcfg.get_section(parents)

        if config:
            for arg in args:
                if arg not in ['asn', 'afi', 'safi', 'vrf']:
                    gv = get_value(arg, config, module)
                    if gv:
                        existing[arg] = gv
                    else:
                        if arg != 'client_to_client' and arg in PARAM_TO_DEFAULT_KEYMAP.keys(
                        ):
                            existing[arg] = PARAM_TO_DEFAULT_KEYMAP.get(arg)
                        else:
                            existing[arg] = gv

            existing['asn'] = existing_asn
            existing['afi'] = module.params['afi']
            existing['safi'] = module.params['safi']
            existing['vrf'] = module.params['vrf']
    else:
        warnings.append(
            "The BGP process {0} didn't exist but the task just created it.".
            format(module.params['asn']))

    return existing
示例#27
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ["evpn", "vni {0} l2".format(module.params["vni"])]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            if arg != "vni":
                if arg == "route_distinguisher":
                    existing[arg] = get_value(arg, config, module)
                else:
                    existing[arg] = get_route_target_value(arg, config, module)

        existing_fix = dict((k, v) for k, v in existing.items() if v)
        if not existing_fix:
            existing = existing_fix

        existing["vni"] = module.params["vni"]

    return existing
示例#28
0
def get_portchannel_mode(interface, protocol, module, netcfg):
    if protocol != 'LACP':
        mode = 'on'
    else:
        netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
        parents = ['interface {0}'.format(interface.capitalize())]
        body = netcfg.get_section(parents)

        mode_list = body.split('\n')

        for line in mode_list:
            this_line = line.strip()
            if this_line.startswith('channel-group'):
                find = this_line
        if 'mode' in find:
            if 'passive' in find:
                mode = 'passive'
            elif 'active' in find:
                mode = 'active'

    return mode
示例#29
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ['evpn', 'vni {0} l2'.format(module.params['vni'])]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            if arg != 'vni':
                if arg == 'route_distinguisher':
                    existing[arg] = get_value(arg, config, module)
                else:
                    existing[arg] = get_route_target_value(arg, config, module)

        existing_fix = dict((k, v) for k, v in existing.items() if v)
        if not existing_fix:
            existing = existing_fix

        existing['vni'] = module.params['vni']

    return existing
示例#30
0
def get_portchannel_mode(interface, protocol, module, netcfg):
    if protocol != 'LACP':
        mode = 'on'
    else:
        netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
        parents = ['interface {0}'.format(interface.capitalize())]
        body = netcfg.get_section(parents)

        mode_list = body.split('\n')

        for line in mode_list:
            this_line = line.strip()
            if this_line.startswith('channel-group'):
                find = this_line
        if 'mode' in find:
            if 'passive' in find:
                mode = 'passive'
            elif 'active' in find:
                mode = 'active'

    return mode
示例#31
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2,
                                 contents=get_config(module, flags=['all']))

    interface_string = 'interface {0}'.format(
        module.params['interface'].lower())
    parents = [interface_string]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            existing[arg] = get_value(arg, config, module)

        existing['interface'] = module.params['interface'].lower()
    else:
        if interface_string in str(netcfg):
            existing['interface'] = module.params['interface'].lower()
            for arg in args:
                existing[arg] = ''
    return existing
示例#32
0
def get_existing(module, args):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))
    parents = ['evpn', 'vni {0} l2'.format(module.params['vni'])]
    config = netcfg.get_section(parents)

    if config:
        for arg in args:
            if arg != 'vni':
                if arg == 'route_distinguisher':
                    existing[arg] = get_value(arg, config, module)
                else:
                    existing[arg] = get_route_target_value(arg, config, module)

        existing_fix = dict((k, v) for k, v in existing.items() if v)
        if existing_fix:
            existing['vni'] = module.params['vni']
        else:
            existing = existing_fix

    return existing
示例#33
0
def map_config_to_obj(want, module):
    objs = list()
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    for w in want:
        parents = ['interface {0}'.format(w['name'])]
        config = netcfg.get_section(parents)
        obj = dict(name=None, ipv4=None, ipv6=None)

        if config:
            match_name = re.findall(r'interface (\S+)', config, re.M)
            if match_name:
                obj['name'] = match_name[0]

            match_ipv4 = re.findall(r'ip address (\S+)', config, re.M)
            if match_ipv4:
                obj['ipv4'] = match_ipv4[0]

            match_ipv6 = re.findall(r'ipv6 address (\S+)', config, re.M)
            if match_ipv6:
                obj['ipv6'] = match_ipv6[0]

        objs.append(obj)
    return objs
def map_config_to_obj(want, module):
    objs = list()
    netcfg = CustomNetworkConfig(indent=2, contents=get_config(module))

    for w in want:
        parents = ["interface {0}".format(w["name"])]
        config = netcfg.get_section(parents)
        obj = dict(name=None, ipv4=None, ipv6=[])

        if config:
            match_name = re.findall(r"interface (\S+)", config, re.M)
            if match_name:
                obj["name"] = normalize_interface(match_name[0])

            match_ipv4 = re.findall(r"ip address (\S+)", config, re.M)
            if match_ipv4:
                obj["ipv4"] = match_ipv4[0]

            match_ipv6 = re.findall(r"ipv6 address (\S+)", config, re.M)
            if match_ipv6:
                obj["ipv6"] = match_ipv6

            objs.append(obj)
    return objs
def get_existing(module, args, warnings):
    existing = {}
    netcfg = CustomNetworkConfig(indent=2,
                                 contents=get_config(module,
                                                     flags=["bgp all"]))

    asn_re = re.compile(r".*router\sbgp\s(?P<existing_asn>\d+(\.\d+)?).*",
                        re.S)
    asn_match = asn_re.match(str(netcfg))

    if asn_match:
        existing_asn = asn_match.group("existing_asn")
        bgp_parent = "router bgp {0}".format(existing_asn)

        if module.params["vrf"] != "default":
            parents = [bgp_parent, "vrf {0}".format(module.params["vrf"])]
        else:
            parents = [bgp_parent]

        config = netcfg.get_section(parents)
        if config:
            for arg in args:
                if arg != "asn" and (module.params["vrf"] == "default"
                                     or arg not in GLOBAL_PARAMS):
                    existing[arg] = get_value(arg, config)

            existing["asn"] = existing_asn
            if module.params["vrf"] == "default":
                existing["vrf"] = "default"

    if (not existing and module.params["vrf"] != "default"
            and module.params["state"] == "present"):
        msg = "VRF {0} doesn't exist.".format(module.params["vrf"])
        warnings.append(msg)

    return existing
示例#36
0
    def get_existing(self, cache_output=None):
        """Update ref with existing command states from the device.
        Store these states in each command's 'existing' key.
        """
        ref = self._ref
        if ref.get('_cli_is_feature_disabled'):
            # Add context to proposed if state is present
            if ref['_state'] in self.present_states:
                [ref['_proposed'].append(ctx) for ctx in ref['_context']]
            return

        show_cmd = ref['_template']['get_command']
        if cache_output:
            output = cache_output
        else:
            output = self.execute_show_command(show_cmd, 'text') or []
            self.cache_existing = output

        # Add additional command context if needed.
        if ref['_context']:
            output = CustomNetworkConfig(indent=2, contents=output)
            output = output.get_section(ref['_context'])

        if not output:
            # Add context to proposed if state is present
            if ref['_state'] in self.present_states:
                [ref['_proposed'].append(ctx) for ctx in ref['_context']]
            return

        # We need to remove the last item in context for state absent case.
        if ref['_state'] in self.absent_states and ref['_context']:
            if ref['_resource_key'] and ref['_resource_key'] == ref['_context'][-1]:
                if ref['_context'][-1] in output:
                    ref['_context'][-1] = 'no ' + ref['_context'][-1]
                else:
                    del ref['_context'][-1]
                return

        # Walk each cmd in ref, use cmd pattern to discover existing cmds
        output = output.split('\n')
        for k in ref['commands']:
            match = self.pattern_match_existing(output, k)
            if not match:
                continue
            ref[k]['existing'] = {}
            for item in match:
                index = match.index(item)
                kind = ref[k]['kind']
                if 'int' == kind:
                    ref[k]['existing'][index] = int(item[0])
                elif 'list' == kind:
                    ref[k]['existing'][index] = [str(i) for i in item[0]]
                elif 'dict' == kind:
                    # The getval pattern should contain regex named group keys that
                    # match up with the setval named placeholder keys; e.g.
                    #   getval: my-cmd (?P<foo>\d+) bar (?P<baz>\d+)
                    #   setval: my-cmd {foo} bar {baz}
                    ref[k]['existing'][index] = {}
                    for key in item.groupdict().keys():
                        ref[k]['existing'][index][key] = str(item.group(key))
                elif 'str' == kind:
                    ref[k]['existing'][index] = item[0]
                else:
                    raise ValueError("get_existing: unknown 'kind' value specified for key '{0}'".format(k))