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']), # this argument is deprecated in favor of setting match: none # it will be removed in a future version force=dict(default=False, type='bool'), config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save=dict(type='bool', default=False), ) argument_spec.update(nxos_argument_spec) mutually_exclusive = [('lines', 'src')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) if module.params['force'] is True: module.params['match'] = 'none' warnings = list() check_args(module, warnings) result = dict(changed=False, warnings=warnings) if module.params['backup']: result['__backup__'] = get_config(module) if any((module.params['src'], module.params['lines'])): run(module, result) if module.params['save']: if not module.check_mode: cmd = {'command': 'copy running-config startup-config', 'output': 'text'} run_commands(module, [cmd]) result['changed'] = True module.exit_json(**result)
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)
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): existing = {} netcfg = get_config(module) try: asn_regex = '.*router\sbgp\s(?P<existing_asn>\d+).*' match_asn = re.match(asn_regex, str(netcfg), re.DOTALL) existing_asn_group = match_asn.groupdict() existing_asn = existing_asn_group['existing_asn'] except AttributeError: existing_asn = '' if 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']: existing[arg] = get_value(arg, config, module) 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): existing = {} netcfg = CustomNetworkConfig(indent=2, contents=get_config(module)) parents = ['vrf context {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: 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 ['afi', 'safi', 'vrf']: existing[arg] = get_value(arg, config, module) existing['afi'] = module.params['afi'] existing['safi'] = module.params['safi'] existing['vrf'] = module.params['vrf'] return existing
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
def get_existing(module, args): existing = {} netcfg = get_config(module) custom = [ 'allowas_in_max', 'send_community', 'additional_paths_send', 'additional_paths_receive', 'advertise_map_exist', 'advertise_map_non_exist', 'filter_list_in', 'filter_list_out', 'max_prefix_limit', 'max_prefix_interval', 'max_prefix_threshold', 'max_prefix_warning', 'next_hop_third_party', 'prefix_list_in', 'prefix_list_out', 'route_map_in', 'route_map_out', 'soft_reconfiguration_in' ] try: asn_regex = '.*router\sbgp\s(?P<existing_asn>\d+).*' match_asn = re.match(asn_regex, str(netcfg), re.DOTALL) existing_asn_group = match_asn.groupdict() existing_asn = existing_asn_group['existing_asn'] except AttributeError: existing_asn = '' if 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']: if arg in custom: existing[arg] = get_custom_value(arg, config, module) else: 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
def get_existing(module, args): existing = {} config = str(get_config(module)) for arg in args: existing[arg] = get_value(arg, config) return existing
def map_config_to_obj(module): obj = [] data = get_config(module, flags=['| section logging']) for line in data.split('\n'): match = re.search(r'logging (\S+)', line, re.M) if match: if match.group(1) in DEST_GROUP: dest = match.group(1) facility = None elif match.group(1) == 'level': match_facility = re.search(r'logging level (\S+)', line, re.M) facility = match_facility.group(1) dest = None else: dest = None facility = None obj.append({'dest': dest, 'name': parse_name(line, dest), 'facility': facility, 'dest_level': parse_dest_level(line, dest, parse_name(line, dest)), 'facility_level': parse_facility_level(line, facility)}) return obj
def get_existing(module, args): existing = {} netcfg = get_config(module) custom = ['assoc_vrf', 'peer_list'] 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']: if arg in custom: existing[arg] = get_custom_value(arg, config, module) else: existing[arg] = get_value(arg, config, module) existing['interface'] = interface_exist existing['vni'] = module.params['vni'] return existing, interface_exist
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+).*', 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']: existing[arg] = get_value(arg, config, module) 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 has_vrf(module, vrf): global _CONFIGURED_VRFS if _CONFIGURED_VRFS is not None: return vrf in _CONFIGURED_VRFS config = get_config(module) _CONFIGURED_VRFS = re.findall(r'vrf context (\S+)', config) return vrf in _CONFIGURED_VRFS
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+).*', 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): 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
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
def get_existing(module, prefix, warnings): key_map = ['tag', 'pref', 'route_name', 'next_hop'] netcfg = get_config(module) parents = 'vrf context {0}'.format(module.params['vrf']) prefix_to_regex = fix_prefix_to_regex(prefix) route_regex = ( '.*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
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+).*', 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
def has_vrf(module, vrf): global _CONFIGURED_VRFS if _CONFIGURED_VRFS is not None: return vrf in _CONFIGURED_VRFS config = get_config(module) _CONFIGURED_VRFS = re.findall('vrf context (\S+)', config) return vrf in _CONFIGURED_VRFS
def get_existing(module): existing = {} config = str(get_config(module)) value = get_value(config, module) if value: existing['ospf'] = value return existing
def get_current_config(module): config = module.params.get('config') if not config and not module.params['force']: flags = [] if module.params['include_defaults']: flags.append('all') config = get_config(module, flags) return config
def get_running_config(module): contents = module.params['config'] if not contents: flags = [] if module.params['defaults']: flags.append('all') contents = get_config(module, flags=flags) return NetworkConfig(indent=2, contents=contents)
def get_running_config(module, config=None): contents = module.params['running_config'] if not contents: if not module.params['defaults'] and config: contents = config else: flags = ['all'] contents = get_config(module, flags=flags) return NetworkConfig(indent=2, contents=contents)
def peer_link_exists(module): found = False run = get_config(module, flags=['section vpc']) vpc_list = run.split('\n') for each in vpc_list: if 'peer-link' in each: found = True return found
def get_vni(vlanid, module): flags = str('all | section vlan.{0}'.format(vlanid)).split(' ') body = get_config(module, flags=flags) value = '' if body: REGEX = re.compile(r'(?:vn-segment\s)(?P<value>.*)$', re.M) if 'vn-segment' in body: value = REGEX.search(body).group('value') return value
def get_vni(vlanid, module): flags = str('all | section vlan.{0}'.format(vlanid)).split(' ') body = get_config(module, flags=flags) #command = 'show run all | section vlan.{0}'.format(vlanid) #body = execute_show_command(command, module, command_type='cli_show_ascii')[0] value = '' if body: REGEX = re.compile(r'(?:vn-segment\s)(?P<value>.*)$', re.M) if 'vn-segment' in body: value = REGEX.search(body).group('value') return value
def get_existing(module, args): existing = {} netcfg = get_config(module) 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 = {} config = str(get_config(module)) for arg in args: command = PARAM_TO_COMMAND_KEYMAP[arg] has_command = re.findall(r'(?:{0}\s)(?P<value>.*)$'.format(command), config, re.M) value = '' if has_command: value = has_command[0] existing[arg] = value return existing
def get_existing(module, args): existing = {} config = str(get_config(module)) for arg in args: command = PARAM_TO_COMMAND_KEYMAP[arg] has_command = re.search(r'^{0}\s(?P<value>.*)$'.format(command), config, re.M) value = '' if has_command: value = has_command.group('value') existing[arg] = value return existing
def get_existing(module, args): existing = {} netcfg = 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
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)) 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
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 state_absent(module, candidate, prefix): netcfg = get_config(module) commands = list() parents = 'vrf context {0}'.format(module.params['vrf']) invoke('set_route', module, commands, prefix) if module.params['vrf'] == 'default': config = netcfg.get_section(commands[0]) if config: invoke('remove_route', module, commands, config, prefix) candidate.add(commands, parents=[]) else: config = netcfg.get_section(parents) splitted_config = config.split('\n') splitted_config = map(str.strip, splitted_config) if commands[0] in splitted_config: invoke('remove_route', module, commands, config, prefix) candidate.add(commands, parents=[parents])
def map_config_to_obj(module): config = get_config(module) configobj = NetworkConfig(indent=2, contents=config) vrf_config = {} vrfs = re.findall('^vrf context (\S+)$', config, re.M) for vrf in vrfs: config_data = configobj.get_block_config(path=['vrf context %s' % vrf]) vrf_config[vrf] = config_data return { 'hostname': parse_hostname(config), 'domain_lookup': 'no ip domain-lookup' not in config, 'domain_name': parse_domain_name(config, vrf_config), 'domain_search': parse_domain_search(config, vrf_config), 'name_servers': parse_name_servers(config, vrf_config) }
def get_existing(module, args): existing = {} netcfg = get_config(module) try: asn_regex = '.*router\sbgp\s(?P<existing_asn>\d+).*' match_asn = re.match(asn_regex, str(netcfg), re.DOTALL) existing_asn_group = match_asn.groupdict() existing_asn = existing_asn_group['existing_asn'] except AttributeError: existing_asn = '' if 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': if module.params['vrf'] != 'default': if arg not in GLOBAL_PARAMS: existing[arg] = get_value(arg, config) else: existing[arg] = get_value(arg, config) existing['asn'] = existing_asn if module.params['vrf'] == 'default': existing['vrf'] = 'default' else: if (module.params['state'] == 'present' and module.params['vrf'] != 'default'): msg = ("VRF {0} doesn't exist. ".format(module.params['vrf'])) WARNINGS.append(msg) else: if (module.params['state'] == 'present' and module.params['vrf'] != 'default'): msg = ("VRF {0} doesn't exist. ".format(module.params['vrf'])) WARNINGS.append(msg) return existing
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
def map_config_to_obj(module): config = get_config(module) configobj = NetworkConfig(indent=2, contents=config) vrf_config = {} vrfs = re.findall('^vrf context (\S+)$', config, re.M) for vrf in vrfs: config_data = configobj.get_block_config(path=['vrf context %s' % vrf]) vrf_config[vrf] = config_data return { 'hostname': parse_hostname(config), 'domain_lookup': 'no ip domain-lookup' not in config, 'domain_name': parse_domain_name(config, vrf_config), 'domain_search': parse_domain_search(config, vrf_config), 'name_servers': parse_name_servers(config, vrf_config, vrfs), 'system_mtu': parse_system_mtu(config) }
def get_existing(module, args): existing = {} netcfg = CustomNetworkConfig(indent=2, contents=get_config(module)) 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
def get_existing(module, args): existing = {} netcfg = get_config(module) custom = [ 'log_neighbor_changes', 'pwd', 'pwd_type', 'remove_private_as', 'timers_holdtime', 'timers_keepalive' ] try: asn_regex = '.*router\sbgp\s(?P<existing_asn>\d+).*' match_asn = re.match(asn_regex, str(netcfg), re.DOTALL) existing_asn_group = match_asn.groupdict() existing_asn = existing_asn_group['existing_asn'] except AttributeError: existing_asn = '' if 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']: if arg in custom: existing[arg] = get_custom_value(arg, config, module) else: existing[arg] = get_value(arg, config, module) 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
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
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
def main(): argument_spec = dict( nv_overlay_evpn=dict(required=True, type='bool'), # deprecated in Ans2.3 include_defaults=dict(), config=dict(), save=dict() ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() check_args(module, warnings) if warnings: result['warnings'] = warnings config = get_config(module) commands = list() if module.params['nv_overlay_evpn'] is True: if 'nv overlay evpn' not in config: commands.append('nv overlay evpn') elif 'nv overlay evpn' in config: commands.append('no nv overlay evpn') if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True result['commands'] = commands module.exit_json(**result)
def get_existing(module, args): existing = {} config = str(get_config(module)) address = module.params['rp_address'] pim_address_re = r'ip pim rp-address (?P<value>.*)$' for line in re.findall(pim_address_re, config, re.M): values = line.split() if values[0] != address: continue existing['bidir'] = existing.get('bidir') or 'bidir' in line if len(values) > 2: value = values[2] if values[1] == 'route-map': existing['route_map'] = value elif values[1] == 'prefix-list': existing['prefix_list'] = value elif values[1] == 'group-list': existing['group_list'] = value return existing
def get_vpc(module): body = run_commands(module, ['show vpc | json'])[0] domain = str(body['vpc-domain-id']) auto_recovery = 'enabled' in str(body['vpc-auto-recovery-status']).lower() vpc = {} if domain != 'not configured': delay_restore = None pkl_src = None role_priority = '32667' system_priority = None pkl_dest = None pkl_vrf = None peer_gw = False run = get_config(module, flags=['section vpc']) if run: vpc_list = run.split('\n') for each in vpc_list: if 'delay restore' in each: line = each.split() if len(line) == 3: delay_restore = line[-1] if 'peer-keepalive destination' in each: line = each.split() pkl_dest = line[2] for word in line: if 'source' in word: index = line.index(word) pkl_src = line[index + 1] if 'role priority' in each: line = each.split() role_priority = line[-1] if 'system-priority' in each: line = each.split() system_priority = line[-1] if 'peer-gateway' in each: peer_gw = True body = run_commands(module, ['show vpc peer-keepalive | json'])[0] if body: pkl_dest = body['vpc-keepalive-dest'] if 'N/A' in pkl_dest: pkl_dest = None elif len(pkl_dest) == 2: pkl_dest = pkl_dest[0] pkl_vrf = str(body['vpc-keepalive-vrf']) vpc['domain'] = domain vpc['auto_recovery'] = auto_recovery vpc['delay_restore'] = delay_restore vpc['pkl_src'] = pkl_src vpc['role_priority'] = role_priority vpc['system_priority'] = system_priority vpc['pkl_dest'] = pkl_dest vpc['pkl_vrf'] = pkl_vrf vpc['peer_gw'] = peer_gw return vpc
def populate(self): super(Config, self).populate() self.facts['config'] = get_config(self.module)
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']), 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'], default='never'), diff_against=dict(choices=['running', 'startup', 'intended']), diff_ignore_lines=dict(type='list'), # 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(nxos_argument_spec) mutually_exclusive = [('lines', 'src'), ('save', 'save_when')] 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) warnings = list() nxos_check_args(module, warnings) result = {'changed': False, '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': config = get_running_config(module, config) 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 if not module.check_mode: load_config(module, commands) result['changed'] = True running_config = None startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save']: module.params['save_when'] = 'always' if module.params['save_when'] != 'never': output = run_commands(module, ['show running-config', 'show startup-config']) 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, 'show running-config') 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, 'show startup-config') contents = output[0] else: contents = output[0] 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)
def get_pim_interface(module, interface): pim_interface = {} command = 'show ip pim interface {0}'.format(interface) body = execute_show_command(command, module, text=True) if body: if 'not running' not in body[0]: body = execute_show_command(command, module) # Some nxos platforms have the TABLE_vrf/ROW_vrf key and some don't try: get_data = body[0]['TABLE_vrf']['ROW_vrf']['TABLE_iod']['ROW_iod'] except (KeyError, AttributeError, TypeError, IndexError): try: get_data = body[0]['TABLE_iod']['ROW_iod'] except (KeyError, AttributeError, TypeError, IndexError): return pim_interface if isinstance(get_data.get('dr-priority'), list): pim_interface['dr_prio'] = get_data.get('dr-priority')[0] else: pim_interface['dr_prio'] = str(get_data.get('dr-priority')) hello_interval = get_data.get('hello-interval-sec') if hello_interval: hello_interval_msec = int(get_data.get('hello-interval-sec')) * 1000 pim_interface['hello_interval'] = str(hello_interval_msec) border = get_data.get('is-border') if border == 'true': pim_interface['border'] = True elif border == 'false': pim_interface['border'] = False isauth = get_data.get('isauth-config') if isauth == 'true': pim_interface['isauth'] = True elif isauth == 'false': pim_interface['isauth'] = False pim_interface['neighbor_policy'] = get_data.get('nbr-policy-name') if pim_interface['neighbor_policy'] == 'none configured': pim_interface['neighbor_policy'] = None jp_in_policy = get_data.get('jp-in-policy-name') pim_interface['jp_policy_in'] = jp_in_policy if jp_in_policy == 'none configured': pim_interface['jp_policy_in'] = None pim_interface['jp_policy_out'] = get_jp_policy_out(module, interface) body = get_config(module, flags=['interface {0}'.format(interface)]) jp_configs = [] neigh = None if body: all_lines = body.splitlines() for each in all_lines: if 'jp-policy' in each: jp_configs.append(str(each.strip())) elif 'neighbor-policy' in each: neigh = str(each) elif 'sparse-mode' in each: pim_interface['sparse'] = True pim_interface['neighbor_type'] = None neigh_type = None if neigh: if 'prefix-list' in neigh: neigh_type = 'prefix' else: neigh_type = 'routemap' pim_interface['neighbor_type'] = neigh_type len_existing = len(jp_configs) list_of_prefix_type = len([x for x in jp_configs if 'prefix-list' in x]) jp_type_in = None jp_type_out = None jp_bidir = False if len_existing == 1: # determine type last_word = jp_configs[0].split(' ')[-1] if last_word == 'in': if list_of_prefix_type: jp_type_in = 'prefix' else: jp_type_in = 'routemap' elif last_word == 'out': if list_of_prefix_type: jp_type_out = 'prefix' else: jp_type_out = 'routemap' else: jp_bidir = True if list_of_prefix_type: jp_type_in = 'prefix' jp_type_out = 'routemap' else: jp_type_in = 'routemap' jp_type_out = 'routemap' else: for each in jp_configs: last_word = each.split(' ')[-1] if last_word == 'in': if 'prefix-list' in each: jp_type_in = 'prefix' else: jp_type_in = 'routemap' elif last_word == 'out': if 'prefix-list' in each: jp_type_out = 'prefix' else: jp_type_out = 'routemap' pim_interface['jp_type_in'] = jp_type_in pim_interface['jp_type_out'] = jp_type_out pim_interface['jp_bidir'] = jp_bidir return pim_interface
def main(): argument_spec = dict( vrf=dict(required=True), afi=dict(required=True, choices=['ipv4', 'ipv6']), route_target_both_auto_evpn=dict(required=False, type='bool'), state=dict(choices=['present', 'absent'], default='present'), m_facts=dict(default=False, type='bool', removed_in_version="2.4"), safi=dict(choices=['unicast', 'multicast'], removed_in_version="2.4"), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False, 'warnings': warnings} config_text = get_config(module) config = NetworkConfig(indent=2, contents=config_text) path = ['vrf context %s' % module.params['vrf'], 'address-family %s unicast' % module.params['afi']] try: current = config.get_block_config(path) except ValueError: current = None commands = list() if current and module.params['state'] == 'absent': commands.append('no address-family %s unicast' % module.params['afi']) elif module.params['state'] == 'present': if current: have = 'route-target both auto evpn' in current want = bool(module.params['route_target_both_auto_evpn']) if want and not have: commands.append('address-family %s unicast' % module.params['afi']) commands.append('route-target both auto evpn') elif have and not want: commands.append('address-family %s unicast' % module.params['afi']) commands.append('no route-target both auto evpn') else: commands.append('address-family %s unicast' % module.params['afi']) if module.params['route_target_both_auto_evpn']: commands.append('route-target both auto evpn') if commands: commands.insert(0, 'vrf context %s' % module.params['vrf']) if not module.check_mode: load_config(module, commands) result['changed'] = True result['commands'] = commands module.exit_json(**result)