diff --git a/plugins/module_utils/network/vyos/config/bgp_global/bgp_global.py b/plugins/module_utils/network/vyos/config/bgp_global/bgp_global.py index 1dd6352c..46dfafcf 100644 --- a/plugins/module_utils/network/vyos/config/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/vyos/config/bgp_global/bgp_global.py @@ -1,491 +1,502 @@ # # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function import re __metaclass__ = type """ The vyos_bgp_global config file. It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary to bring the current configuration to its desired end-state is created. """ from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module import ( ResourceModule, ) from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( dict_merge, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import Facts from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.bgp_global import ( Bgp_globalTemplate, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.bgp_global_14 import ( Bgp_globalTemplate14, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.version import ( LooseVersion, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import get_os_version class Bgp_global(ResourceModule): """ The vyos_bgp_global config class """ - def __init__(self, module): + def __init__(self, module, vrf=None): super(Bgp_global, self).__init__( empty_fact_val={}, facts_module=Facts(module), module=module, resource="bgp_global", tmplt=Bgp_globalTemplate(), ) self.parsers = [] + # the VRF whose BGP instance this is (vyos_vrf), None for the global instance + self.vrf = vrf def _validate_template(self): version = get_os_version(self._module) if LooseVersion(version) >= LooseVersion("1.4"): self._tmplt = Bgp_globalTemplate14() else: self._tmplt = Bgp_globalTemplate() def parse(self): """override parse to check template""" self._validate_template() return super().parse() def get_parser(self, name): """get_parsers""" self._validate_template() return super().get_parser(name) def execute_module(self): """Execute the module :rtype: A dictionary :returns: The result from module execution """ - version = get_os_version(self._module) - if LooseVersion(version) >= LooseVersion("1.4"): - self._asn_mod = "" - else: - self._asn_mod = " " + str(self.have.get("as_number")) self._validate_template() if self.state not in ["parsed", "gathered"]: self.generate_commands() self.run_commands() return self.result def generate_commands(self): """Generate configuration commands to send based on want, have and desired state. """ wantd = {} haved = {} + # set here, not in execute_module: vyos_vrf calls generate_commands directly + if LooseVersion(get_os_version(self._module)) >= LooseVersion("1.4"): + self._asn_mod = "" + else: + self._asn_mod = " " + str(self.have.get("as_number")) # remote_as is an AS number or "external"/"internal"; numbers are compared as int for neighbor in self.want.get("neighbor", []): if "remote_as" in neighbor: neighbor["remote_as"] = self._remote_as(neighbor["address"], neighbor["remote_as"]) v6only = neighbor.get("interface", {}).get("v6only", {}) if "remote_as" in v6only: v6only["remote_as"] = self._remote_as(neighbor["address"], v6only["remote_as"]) # Options without a CLI path on VyOS 1.4 and later are dropped from want, with a # warning. The version is only checked when one of them is set (no device access # otherwise, e.g. for state rendered). default = self.want.get("bgp_params", {}).get("default", {}) neighbors = [n for n in self.want.get("neighbor", []) if "default_originate" in n] if ("no_ipv4_unicast" in default or neighbors) and LooseVersion( get_os_version(self._module), ) >= LooseVersion("1.4"): # no "parameters default no-ipv4-unicast": FRR always has it if default.pop("no_ipv4_unicast", None) is not None: self._module.warn( "no_ipv4_unicast is ignored: VyOS 1.4 and later always apply it " "(no bgp default ipv4-unicast)", ) if not default: self.want["bgp_params"].pop("default") # default-originate only exists per address family for neighbor in neighbors: neighbor.pop("default_originate") self._module.warn( "neighbor {0}: default_originate is ignored: VyOS 1.4 and later only " "support it per address family, see vyos_bgp_address_family".format( neighbor["address"], ), ) if self.want and self.want.get("as_number") is None and self.state != "deleted": self._module.fail_json( msg="as_number is required: VyOS needs a system-as for every BGP " "instance, including the BGP instance of each VRF", ) if ( self.want.get("as_number") == self.have.get("as_number") or not self.have or LooseVersion(get_os_version(self._module)) >= LooseVersion("1.4") ): if self.want: wantd = {self.want["as_number"]: self.want} if self.have: haved = {self.have["as_number"]: self.have} else: self._module.fail_json(msg="Only one bgp instance is allowed per device") # turn all lists of dicts into dicts prior to merge for entry in wantd, haved: self._bgp_global_list_to_dict(entry) # if state is merged, merge want onto have and then compare if self.state == "merged": wantd = dict_merge(haved, wantd) # if state is deleted, empty out wantd and set haved to wantd if self.state == "purged": h_del = {} for k, v in haved.items(): if k in wantd or not wantd: h_del.update({k: v}) for num, entry in h_del.items(): self.commands.append(self._tmplt.render({"as_number": num}, "router", True)) wantd = {} if self.state == "deleted": self._compare(want={}, have=self.have) wantd = {} for k, want in wantd.items(): self._compare(want=want, have=haved.pop(k, {})) def _compare(self, want, have): """Leverages the base class `compare()` method and populates the list of commands to be run by comparing the `want` and `have` data with the `parsers` defined for the Bgp_global network resource. """ if LooseVersion(get_os_version(self._module)) >= LooseVersion("1.4"): self._compare_asn(want, have) parsers = ["maximum_paths", "timers"] self._compare_neighbor(want, have) self._compare_bgp_params(want, have) for name, entry in want.items(): if name != "as_number": self.compare( parsers=parsers, want={"as_number": want["as_number"], name: entry}, have={ "as_number": want["as_number"], name: have.pop(name, {}), }, ) for name, entry in have.items(): if name != "as_number": self.compare( parsers=parsers, want={}, have={"as_number": have["as_number"], name: entry}, ) # Do the negation first command_set = [] for cmd in self.commands: if cmd not in command_set: if "delete" in cmd: command_set.insert(0, cmd) else: command_set.append(cmd) self.commands = command_set def _compare_neighbor(self, want, have): parsers = [ "neighbor.advertisement_interval", "neighbor.allowas_in", "neighbor.as_override", "neighbor.attribute_unchanged.as_path", "neighbor.attribute_unchanged.med", "neighbor.attribute_unchanged.next_hop", "neighbor.capability_dynamic", "neighbor.capability_orf", "neighbor.default_originate", "neighbor.description", "neighbor.interface.v6only.peer_group", "neighbor.interface.v6only.remote_as", "neighbor.disable_capability_negotiation", "neighbor.disable_connected_check", "neighbor.disable_send_community", "neighbor.distribute_list", "neighbor.ebgp_multihop", "neighbor.filter_list", "neighbor.local_as", "neighbor.maximum_prefix", "neighbor.nexthop_self", "neighbor.override_capability", "neighbor.passive", "neighbor.password", + "neighbor.peer_group", "neighbor.peer_group_name", "neighbor.port", "neighbor.prefix_list", "neighbor.remote_as", "neighbor.remove_private_as", "neighbor.route_map", "neighbor.route_reflector_client", "neighbor.route_server_client", "neighbor.shutdown", "neighbor.soft_reconfiguration", "neighbor.strict_capability_match", "neighbor.unsuppress_map", "neighbor.update_source", "neighbor.weight", "neighbor.ttl_security", "neighbor.timers", ] wneigh = want.pop("neighbor", {}) hneigh = have.pop("neighbor", {}) - peer_groups = [n for d in (wneigh, hneigh) for n, e in d.items() if e.get("peer_group")] - first = len(self.commands) - self._compare_neigh_lists(wneigh, hneigh) - - for name, entry in wneigh.items(): + # neighbors and peer groups are keyed by (peer_group, name): see _bgp_global_list_to_dict + for key, entry in wneigh.items(): + first = len(self.commands) + hentry = hneigh.get(key, {}) for k, v in entry.items(): if k == "address": continue - if hneigh.get(name): - h = {"address": name, k: hneigh[name].pop(k, {})} + # the bare "peer-group " node only for a group without other settings + if k == "peer_group" and len(entry) > 2: + hentry.pop(k, None) + continue + if hentry: + h = {"address": key[1], k: hentry.pop(k, {})} else: h = {} self.compare( parsers=parsers, want={ "as_number": want["as_number"], - "neighbor": {"address": name, k: v}, + "neighbor": {"address": key[1], k: v}, }, have={"as_number": want["as_number"], "neighbor": h}, ) - for name, entry in hneigh.items(): - if name not in wneigh.keys(): - if self._check_af(name): - msg = "Use the _bgp_address_family module to delete the address_family under neighbor {0}, before replacing/deleting the neighbor.".format( - name, - ) + self._rename_peer_group(key, first) + for key, entry in hneigh.items(): + first = len(self.commands) + if key not in wneigh: + if self._check_af(key): + if key[0]: + # vyos_bgp_address_family only manages neighbor address families + msg = ( + "Remove the address-family settings of peer-group {0} with " + "vyos_config before replacing/deleting the peer group: " + "vyos_bgp_address_family does not manage peer groups.".format(key[1]) + ) + else: + msg = "Use the _bgp_address_family module to delete the address_family under neighbor {0}, before replacing/deleting the neighbor.".format( + key[1], + ) self._module.fail_json(msg=msg) - else: - self.commands.append( - "delete protocols bgp" + self._asn_mod + " neighbor " + name, - ) - continue - for k, v in entry.items(): - self.compare( - parsers=parsers, - want={}, - have={ - "as_number": have["as_number"], - "neighbor": {"address": name, k: v}, - }, - ) - # peer-group definitions are compared like neighbors, then renamed - for i, cmd in enumerate(self.commands[first:], first): - for name in peer_groups: - cmd = re.sub( - r"^(\S+ protocols bgp )neighbor " + re.escape(name) + r"(?= |$)", - r"\1peer-group " + name, - cmd, + self.commands.append( + "delete protocols bgp" + self._asn_mod + " neighbor " + key[1], ) - self.commands[i] = cmd + else: + for k, v in entry.items(): + if k == "peer_group": # the group itself, not one of its settings + continue + self.compare( + parsers=parsers, + want={}, + have={ + "as_number": have["as_number"], + "neighbor": {"address": key[1], k: v}, + }, + ) + self._rename_peer_group(key, first) + + def _rename_peer_group(self, key, first): + """Peer-group definitions are compared with the neighbor parsers: rename the + commands generated for one, from index first on.""" + is_peer_group, name = key + if not is_peer_group: + return + neighbor = re.compile(r"^(\S+ protocols bgp )neighbor " + re.escape(name) + r"(?= |$)") + self.commands[first:] = [ + neighbor.sub(r"\1peer-group " + name, cmd) for cmd in self.commands[first:] + ] def _compare_bgp_params(self, want, have): parsers = [ "bgp_params.always_compare_med", "bgp_params.bestpath.as_path", "bgp_params.bestpath.compare_routerid", "bgp_params.bestpath.med", "bgp_params.cluster_id", "bgp_params.confederation", "bgp_params.dampening_half_life", "bgp_params.dampening_max_suppress_time", "bgp_params.dampening_re_use", "bgp_params.dampening_start_suppress_time", "bgp_params.default", "bgp_params.deterministic_med", "bgp_params.disbale_network_import_check", "bgp_params.enforce_first_as", "bgp_params.graceful_restart", "bgp_params.log_neighbor_changes", "bgp_params.no_client_to_client_reflection", "bgp_params.no_fast_external_failover", "bgp_params.routerid", "bgp_params.scan_time", ] wbgp = want.pop("bgp_params", {}) hbgp = have.pop("bgp_params", {}) # The as-path flags (confed, ignore, multipath-relax) are separate leaves in VyOS: # changing as_path has to delete the flag it replaces. w_as_path = wbgp.get("bestpath", {}).get("as_path") h_as_path = hbgp.get("bestpath", {}).get("as_path") if w_as_path and h_as_path and w_as_path != h_as_path: self.addcmd( { "as_number": want["as_number"], "bgp_params": {"bestpath": {"as_path": h_as_path}}, }, "bgp_params.bestpath.as_path", True, ) for name, entry in wbgp.items(): if name == "confederation": if entry != hbgp.pop(name, {}): self.addcmd( { "as_number": want["as_number"], "bgp_params": {name: entry}, }, "bgp_params.confederation", False, ) elif name == "distance": if entry != hbgp.pop(name, {}): distance_parsers = [ "bgp_params.distance.global", "bgp_params.distance.prefix", ] for distance_type in entry: self.compare( parsers=distance_parsers, want={ "as_number": want["as_number"], "bgp_params": {name: distance_type}, }, have={ "as_number": want["as_number"], "bgp_params": {name: hbgp.pop(name, {})}, }, ) else: self.compare( parsers=parsers, want={ "as_number": want["as_number"], "bgp_params": {name: entry}, }, have={ "as_number": want["as_number"], "bgp_params": {name: hbgp.pop(name, {})}, }, ) if not wbgp and hbgp: self.commands.append("delete protocols bgp" + self._asn_mod + " parameters") hbgp = {} for name, entry in hbgp.items(): if name == "confederation": self.commands.append( "delete protocols bgp" + self._asn_mod + " parameters confederation", ) elif name == "distance": distance_parsers = [ "bgp_params.distance.global", "bgp_params.distance.prefix", ] self.compare( parsers=distance_parsers, want={}, have={ "as_number": have["as_number"], "bgp_params": {name: entry[0]}, }, ) else: self.compare( parsers=parsers, want={}, have={ "as_number": have["as_number"], "bgp_params": {name: entry}, }, ) - def _compare_neigh_lists(self, want, have): - for attrib in [ - "distribute_list", - "filter_list", - "prefix_list", - "route_map", - ]: - wdict = want.pop(attrib, {}) - hdict = have.pop(attrib, {}) - for key, entry in wdict.items(): - if entry != hdict.pop(key, {}): - self.addcmd(entry, "neighbor.{0}".format(attrib), False) - # remove remaining items in have for replaced - for entry in hdict.values(): - self.addcmd(entry, "neighbor.{0}".format(attrib), True) - def _bgp_global_list_to_dict(self, entry): for name, proc in entry.items(): if "neighbor" in proc: neigh_dict = {} for entry in proc.get("neighbor", []): - neigh_dict.update({entry["address"]: entry}) + # a peer group and a neighbor may have the same name + key = (bool(entry.get("peer_group")), entry["address"]) + neigh_dict.update({key: entry}) proc["neighbor"] = neigh_dict if "network" in proc: network_dict = {} for entry in proc.get("network", []): network_dict.update({entry["address"]: entry}) proc["network"] = network_dict if "aggregate_address" in proc: agg_dict = {} for entry in proc.get("aggregate_address", []): agg_dict.update({entry["prefix"]: entry}) proc["aggregate_address"] = agg_dict if "redistribute" in proc: redis_dict = {} for entry in proc.get("redistribute", []): redis_dict.update({entry["protocol"]: entry}) proc["redistribute"] = redis_dict def _compare_asn(self, want, have): if want.get("as_number") and not have.get("as_number"): self.commands.append( "set protocols bgp " + "system-as" + " " + str(want.get("as_number")), ) - def _check_af(self, neighbor): + def _check_af(self, key): if not self._connection: return False + is_peer_group, name = key + scope = "vrf name {0} ".format(self.vrf) if self.vrf else "" af_line = re.compile( - r"^set protocols bgp (?:\d+ )?(?:neighbor|peer-group) " - + re.escape(neighbor) + r"^set " + + re.escape(scope) + + r"protocols bgp (?:\d+ )?" + + ("peer-group " if is_peer_group else "neighbor ") + + re.escape(name) + r" address-family\b", ) return any(af_line.match(line) for line in self._get_config(self._connection).splitlines()) def _get_config(self, connection): - return connection.get('show configuration commands | match "set protocols bgp"') + return connection.get('show configuration commands | match "protocols bgp"') def _remote_as(self, address, value): if str(value) in ("external", "internal"): return str(value) if str(value).isdigit() and 1 <= int(value) <= 4294967294: return int(value) self._module.fail_json( msg="neighbor {0}: remote_as must be an AS number (1-4294967294), " "'external' or 'internal', got {1!r}".format(address, value), ) diff --git a/plugins/module_utils/network/vyos/config/vrf/vrf.py b/plugins/module_utils/network/vyos/config/vrf/vrf.py index aa4329d9..846dfc25 100644 --- a/plugins/module_utils/network/vyos/config/vrf/vrf.py +++ b/plugins/module_utils/network/vyos/config/vrf/vrf.py @@ -1,308 +1,308 @@ # # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # from __future__ import absolute_import, division, print_function __metaclass__ = type """ The vyos_vrf config file. It is in this file where the current configuration (as dict) is compared to the provided configuration (as dict) and the command set necessary to bring the current configuration to its desired end-state is created. """ from copy import deepcopy from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module import ( ResourceModule, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global.bgp_global import ( Bgp_global, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.ospfv2.ospfv2 import ( Ospfv2, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.ospfv3.ospfv3 import ( Ospfv3, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.static_routes.static_routes import ( Static_routes, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import Facts from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.vrf import ( VrfTemplate, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import combine from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.version import ( LooseVersion, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import get_os_version class Vrf(ResourceModule): """ The vyos_vrf config class """ def __init__(self, module): super(Vrf, self).__init__( empty_fact_val={}, facts_module=Facts(module), module=module, resource="vrf", tmplt=VrfTemplate(), ) self.parsers = [ "bind_to_all", ] def _validate_template(self): version = get_os_version(self._module) if LooseVersion(version) >= LooseVersion("1.4"): self._tmplt = VrfTemplate() else: self._module.fail_json(msg="VRF is not supported in this version of VyOS") def parse(self): """override parse to check template""" self._validate_template() return super().parse() def get_parser(self, name): """get_parsers""" self._validate_template() return super().get_parser(name) def execute_module(self): """Execute the module :rtype: A dictionary :returns: The result from module execution """ if self.state not in ["parsed", "gathered"]: self.generate_commands() self.run_commands() return self.result def generate_commands(self): """Generate configuration commands to send based on want, have and desired state. """ wantd = {} haved = {} wantd = deepcopy(self.want) haved = deepcopy(self.have) # if state is merged, merge want onto have and then compare if self.state in ["merged", "replaced"]: wantd = combine(haved, wantd, recursive=True) # if state is deleted, delete and empty out wantd if self.state == "deleted": w = deepcopy(wantd) if w == {} and haved != {}: self.commands = ["delete vrf"] return for k, want in w.items(): if not (k in haved and haved[k]): del wantd[k] else: if isinstance(want, list): for entry in want: wname = entry.get("name") haved["instances"] = [ i for i in haved.get("instances", []) if i.get("name") != wname ] self.commands.append("delete vrf name {}".format(wname)) else: self.commands.append("delete vrf {}".format(k.replace("_", "-"))) del wantd[k] if self.state == "overridden": w = deepcopy(wantd) h = deepcopy(haved) for k, want in w.items(): if k in haved and haved[k] != want: if isinstance(want, list): for entry in want: wname = entry.get("name") hdict = next( (inst for inst in haved["instances"] if inst["name"] == wname), None, ) wantc = self._canonicalise(entry) havec = self._canonicalise(hdict or {}) if wantc != havec: haved["instances"] = [ i for i in haved.get("instances", []) if i.get("name") != wname ] self.commands.append("delete vrf name {}".format(wname)) self.commands.append("commit") for k, want in wantd.items(): if isinstance(want, list): self._compare_instances(want=want, have=haved.pop(k, {})) self.compare( parsers=self.parsers, want={k: want}, have={k: haved.pop(k, {})}, ) def _compare_instances(self, want, have): """Compare the instances of the VRF""" parsers = [ "table_id", "vni", "description", "disable_vrf", ] for entry in want: h = {} wname = entry.get("name") h = { k: v for vrf in have if vrf.get("name") == wname for k, v in vrf.items() if k != "address_family" } self.compare(parsers=parsers, want=entry, have=h) if "address_family" in entry: wafi = {"name": wname, "address_family": entry.get("address_family", [])} hdict = next((d for d in have if d.get("name") == wname), None) hafi = { "name": (hdict or {"name": wname})["name"], "address_family": hdict.get("address_family", []) if hdict else [], } self._compare_addr_family(wafi, hafi) if "protocols" in entry: for protocol_name in entry["protocols"]: w_p_dict = entry["protocols"][protocol_name] h_p_dict = next( ( v.get("protocols", {}).get(protocol_name, {}) for v in have if v.get("name") == wname ), {}, ) if protocol_name == "bgp": - bgp_module = Bgp_global(self._module) + bgp_module = Bgp_global(self._module, vrf=wname) bgp_module._validate_template() bgp_module.want = w_p_dict bgp_module.have = h_p_dict bgp_module.generate_commands() protocol_commands = bgp_module.commands elif protocol_name == "ospf": ospfv2_module = Ospfv2(self._module) ospfv2_module._module.params["config"] = w_p_dict ospfv2_module.state = self.state protocol_commands = ospfv2_module.set_config(h_p_dict) elif protocol_name == "ospfv3": ospfv3_module = Ospfv3(self._module) ospfv3_module._module.params["config"] = w_p_dict ospfv3_module.state = self.state protocol_commands = ospfv3_module.set_config(h_p_dict) elif protocol_name == "static": static_routes_module = Static_routes(self._module) static_routes_module._module.params["config"] = w_p_dict static_routes_module.state = self.state protocol_commands = static_routes_module.set_config(h_p_dict) else: self._module.fail_json( msg="The protocol {} is not supported".format(protocol_name), ) self.commands.extend( [ cmd.replace("protocols", "vrf name " + wname + " protocols", 1) for cmd in protocol_commands ], ) def _compare_addr_family(self, want, have): """Compare the address families of the VRF""" afi_parsers = [ "disable_forwarding", "disable_nht", ] wafi = self.afi_to_list(want) hafi = self.afi_to_list(have) lookup = {(d["name"], d["afi"]): d for d in hafi} pairs = [(d1, lookup.get((d1["name"], d1["afi"]), {})) for d1 in wafi] for wafd, hafd in pairs: if "route_maps" in wafd: self._compare_route_maps(wafd, hafd) self.compare(parsers=afi_parsers, want=wafd, have=hafd) def afi_to_list(self, data): """Convert address family dict to list""" return [ {"name": data["name"], **{**af, "afi": "ip" if af["afi"] == "ipv4" else af["afi"]}} for af in data["address_family"] ] def _compare_route_maps(self, wafd, hafd): want_rms = wafd.get("route_maps", []) have_rms = hafd.get("route_maps", []) for want in want_rms: match = next( ( h for h in have_rms if h["rm_name"] == want["rm_name"] and h["protocol"] == want["protocol"] ), {}, ) base = {"name": wafd["name"], "afi": wafd["afi"]} self.compare( parsers="route_maps", want={**base, "route_maps": want}, have={**base, "route_maps": match}, ) def _canonicalise(self, obj): if isinstance(obj, dict): return {k: self._canonicalise(v) for k, v in obj.items()} if isinstance(obj, list): if not obj: return obj if not isinstance(obj[0], dict): return sorted(obj) canon = [self._canonicalise(i) for i in obj] def sort_key(d): for k in ("name", "address", "afi", "area_id", "neighbor_id", "dest"): if k in d: return d[k] return tuple(sorted(d.items())) return sorted(canon, key=sort_key) return obj diff --git a/plugins/module_utils/network/vyos/facts/bgp_global/bgp_global.py b/plugins/module_utils/network/vyos/facts/bgp_global/bgp_global.py index f05968a2..c23940e2 100644 --- a/plugins/module_utils/network/vyos/facts/bgp_global/bgp_global.py +++ b/plugins/module_utils/network/vyos/facts/bgp_global/bgp_global.py @@ -1,101 +1,114 @@ # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type """ The vyos bgp_global fact class It is in this file the configuration is collected from the device for a given resource, parsed, and the facts tree is populated based on the configuration. """ import re from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.bgp_global.bgp_global import ( Bgp_globalArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.bgp_global import ( Bgp_globalTemplate, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.rm_templates.bgp_global_14 import ( Bgp_globalTemplate14, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.version import ( LooseVersion, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import get_os_version class Bgp_globalFacts(object): """The vyos bgp_global facts class""" def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = Bgp_globalArgs.argument_spec def get_device_data(self, connection): return connection.get('show configuration commands | match "set protocols bgp"') def populate_facts(self, connection, ansible_facts, data=None): """Populate the facts for Bgp_global network resource :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ facts = {} objs = {} config_lines = [] if not data: data = self.get_device_data(connection) + group_lines = [] peer_groups = set() for resource in data.splitlines(): - if "address-family" not in resource: - line = re.sub("'", "", resource) - # parse peer-group definitions with the neighbor parsers - match = re.match(r"^set protocols bgp peer-group (\S+)(.*)$", line) - if match: - peer_groups.add(match.group(1)) - line = "set protocols bgp neighbor " + "".join(match.groups()) + line = re.sub("'", "", resource) + match = re.match(r"^set protocols bgp peer-group (\S+)(.*)$", line) + if match: + # every peer group, also one with only address-family settings or none + peer_groups.add(match.group(1)) + if "address-family" in line: + continue + if match: + # parse peer-group definitions with the neighbor parsers, apart from the + # neighbors: a peer group and a neighbor may have the same name + group_lines.append("set protocols bgp neighbor " + "".join(match.groups())) + else: config_lines.append(line) if LooseVersion(get_os_version(self._module)) >= LooseVersion("1.4"): - bgp_global_parser = Bgp_globalTemplate14(lines=config_lines, module=self._module) + template = Bgp_globalTemplate14 else: - bgp_global_parser = Bgp_globalTemplate(lines=config_lines, module=self._module) - + template = Bgp_globalTemplate + bgp_global_parser = template(lines=config_lines, module=self._module) objs = bgp_global_parser.parse() - if "neighbor" in objs: - for name in peer_groups & set(objs["neighbor"]): - objs["neighbor"][name]["peer_group"] = True - objs["neighbor"] = list(objs["neighbor"].values()) - objs["neighbor"] = sorted(objs["neighbor"], key=lambda k: k["address"]) + groups = template(lines=group_lines, module=self._module).parse().get("neighbor", {}) + for name in peer_groups: + # a group without global settings gets an entry of its own + groups.setdefault(name, {"address": name})["peer_group"] = True + neighbors = list(objs.get("neighbor", {}).values()) + list(groups.values()) + + if neighbors: + objs["neighbor"] = sorted( + neighbors, + key=lambda k: (k["address"], bool(k.get("peer_group"))), + ) + if "network" in objs: objs["network"] = sorted(objs["network"], key=lambda k: k["address"]) if "aggregate_address" in objs: objs["aggregate_address"] = sorted(objs["aggregate_address"], key=lambda k: k["prefix"]) ansible_facts["ansible_network_resources"].pop("bgp_global", None) params = utils.remove_empties( bgp_global_parser.validate_config(self.argument_spec, {"config": objs}, redact=True), ) facts["bgp_global"] = params.get("config", []) ansible_facts["ansible_network_resources"].update(facts) return ansible_facts diff --git a/plugins/module_utils/network/vyos/rm_templates/bgp_global.py b/plugins/module_utils/network/vyos/rm_templates/bgp_global.py index d9ee793e..c48887c3 100644 --- a/plugins/module_utils/network/vyos/rm_templates/bgp_global.py +++ b/plugins/module_utils/network/vyos/rm_templates/bgp_global.py @@ -1,1888 +1,1911 @@ # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type """ The Bgp_global parser templates file. This contains a list of parser definitions and associated functions that facilitates both facts gathering and native command generation for the given network resource. """ import re from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.network_template import ( NetworkTemplate, ) def _tmplt_bgp_params_confederation(config_data): command = [] for list_el in config_data["bgp_params"]["confederation"]: for k, v in list_el.items(): command.append( "protocols bgp {as_number} parameters confederation ".format(**config_data) + k + " " + str(v), ) return command def _tmplt_bgp_maximum_paths(config_data): command = [] for list_el in config_data["maximum_paths"]: command.append( "protocols bgp {as_number} maximum-paths ".format(**config_data) + list_el["path"] + " " + str(list_el["count"]), ) return command def _tmplt_delete_bgp_maximum_paths(config_data): command = "protocols bgp {as_number} maximum-paths".format(**config_data) return command def _tmplt_bgp_params_default(config_data): command = "protocols bgp {as_number} parameters default".format(**config_data) if config_data["bgp_params"]["default"].get("no_ipv4_unicast"): command += " no-ipv4-unicast" if config_data["bgp_params"]["default"].get("local_pref"): command += " local-pref {local_pref}".format(**config_data["bgp_params"]["default"]) return command def _tmplt_bgp_neighbor_timers(config_data): command = [] for k, v in config_data["neighbor"]["timers"].items(): command.append( "protocols bgp {as_number} neighbor ".format(**config_data) + config_data["neighbor"]["address"] + " timers " + k + " " + str(v), ) return command def _tmplt_bgp_timers(config_data): command = [] for k, v in config_data["timers"].items(): command.append( "protocols bgp {as_number} ".format(**config_data) + "timers " + k + " " + str(v), ) return command def _tmplt_bgp_neighbor_attribute_unchanged_as_path(config_data): command = "protocols bgp {as_number} ".format( **config_data, ) + "neighbor {address} attribute-unchanged as-path".format(**config_data["neighbor"]) return command def _tmplt_bgp_neighbor_attribute_unchanged_med(config_data): command = "protocols bgp {as_number} ".format( **config_data, ) + "neighbor {address} attribute-unchanged med".format(**config_data["neighbor"]) return command def _tmplt_bgp_neighbor_attribute_unchanged_next_hop(config_data): command = "protocols bgp {as_number} ".format( **config_data, ) + "neighbor {address} attribute-unchanged next-hop".format(**config_data["neighbor"]) return command def _tmplt_bgp_neighbor_distribute_list(config_data): command = [] for list_el in config_data["neighbor"]["distribute_list"]: command.append( "protocols bgp {as_number} ".format(**config_data) + "neighbor {address} distribute-list ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["acl"]), ) return command def _tmplt_bgp_neighbor_route_map(config_data): command = [] for list_el in config_data["neighbor"]["route_map"]: command.append( "protocols bgp {as_number} ".format(**config_data) + "neighbor {address} route-map ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["route_map"]), ) return command def _tmplt_bgp_neighbor_prefix_list(config_data): command = [] for list_el in config_data["neighbor"]["prefix_list"]: command.append( "protocols bgp {as_number} ".format(**config_data) + "neighbor {address} prefix-list ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["prefix_list"]), ) return command def _tmplt_bgp_neighbor_filter_list(config_data): command = [] for list_el in config_data["neighbor"]["filter_list"]: command.append( "protocols bgp {as_number} ".format(**config_data) + "neighbor {address} filter-list ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["path_list"]), ) return command def _tmplt_bgp_params_distance(config_data): command = ( "protocols bgp {as_number} parameters distance global ".format(**config_data) + config_data["bgp_params"]["distance"]["type"] + " " + str(config_data["bgp_params"]["distance"]["value"]) ) return command class Bgp_globalTemplate(NetworkTemplate): def __init__(self, lines=None, module=None): prefix = {"set": "set", "remove": "delete"} super(Bgp_globalTemplate, self).__init__( lines=lines, tmplt=self, prefix=prefix, module=module, ) # fmt: off PARSERS = [ { "name": "router", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }}", "compval": "as_number", "result": { "as_number": "{{ as_num }}", }, }, { "name": "maximum_paths", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+maximum-paths \s+(?Pebgp|ibgp) \s+(?P\d+) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_maximum_paths, "remval": _tmplt_delete_bgp_maximum_paths, "compval": "maximum_paths", "result": { "as_number": "{{ as_num }}", "maximum_paths": [ { "path": "{{ path }}", "count": "{{ count }}", }, ], }, }, { "name": "neighbor.advertisement_interval", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+advertisement-interval \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} advertisement-interval {{ neighbor.advertisement_interval }}", "remval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} advertisement-interval", "compval": "neighbor.advertisement_interval", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "advertisement_interval": "{{ interval }}", }, }, }, }, { "name": "neighbor.allowas_in", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+allowas-in \s+number \s+(?P\'\d+\') *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} allowas-in number {{ neighbor.allowas_in }}", "compval": "neighbor.allowas_in", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "allowas_in": "{{ count }}", }, }, }, }, { "name": "neighbor.as_override", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+as-override *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} as-override", "compval": "neighbor.as_override", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "as_override": "{{ True }}", }, }, }, }, { "name": "neighbor.attribute_unchanged.as_path", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+attribute-unchanged \s+(?Pas-path) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_attribute_unchanged_as_path, "compval": "neighbor.attribute_unchanged", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "attribute_unchanged": { "{{ 'as_path' }}": "{{ True }}", }, }, }, }, }, { "name": "neighbor.attribute_unchanged.med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+attribute-unchanged \s+(?Pmed) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_attribute_unchanged_med, "compval": "neighbor.attribute_unchanged", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "attribute_unchanged": { "{{ 'med' }}": "{{ True }}", }, }, }, }, }, { "name": "neighbor.attribute_unchanged.next_hop", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+attribute-unchanged \s+(?Pnext-hop) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_attribute_unchanged_next_hop, "compval": "neighbor.attribute_unchanged", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "attribute_unchanged": { "{{ 'next_hop' }}": "{{ True }}", }, }, }, }, }, { "name": "neighbor.capability_dynamic", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+capability \s+(?Pdynamic) *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} capability dynamic", "compval": "neighbor.capability.dynamic", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "capability": { "dynamic": "{{ True if dynamic is defined}}", }, }, }, }, }, { "name": "neighbor.capability_orf", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+capability \s+orf \s+prefix-list \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} capability orf prefix-list {{ neighbor.capability.orf }}", "compval": "neighbor.capability.orf", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "capability": { "orf": "{{ orf }}", }, }, }, }, }, { "name": "neighbor.default_originate", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+default-originate \s+route-map \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} default-originate route-map {{ neighbor.default_originate }}", "compval": "neighbor.advertisement_interval", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "default_originate": "{{ map }}", }, }, }, }, { "name": "neighbor.description", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+description \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} description {{ neighbor.description }}", "compval": "neighbor.description", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "description": "{{ desc }}", }, }, }, }, { "name": "neighbor.disable_capability_negotiation", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+disable-capability-negotiation *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} disable-capability-negotiation", "compval": "neighbor.disable_capability_negotiation", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "disable_capability_negotiation": "{{ True }}", }, }, }, }, { "name": "neighbor.disable_connected_check", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+disable-connected-check *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} disable-connected-check", "compval": "neighbor.disable_connected_check", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "disable_connected_check": "{{ True }}", }, }, }, }, { "name": "neighbor.disable_send_community", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+disable-send-community \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} disable-send-community {{ neighbor.disable_send_community }}", "compval": "neighbor.disable_send_community", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "disable_send_community": "{{ comm }}", }, }, }, }, { "name": "neighbor.distribute_list", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+distribute-list \s+(?Pexport|import) \s+(?P\d+) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_distribute_list, "compval": "neighbor.distribute_list", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "distribute_list": [ { "action": "{{ action }}", "acl": "{{ list }}", }, ], }, }, }, }, { "name": "neighbor.ebgp_multihop", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+ebgp-multihop \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} ebgp-multihop {{ neighbor.ebgp_multihop }}", "compval": "neighbor.ebgp_multihop", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "ebgp_multihop": "{{ hop|int }}", }, }, }, }, { "name": "neighbor.filter_list", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+filter-list \s+(?Pexport|import) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_filter_list, "compval": "neighbor.filter_list", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "filter_list": [ { "action": "{{ action }}", "path_list": "{{ list }}", }, ], }, }, }, }, { "name": "neighbor.local_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+local-as \s+(?P\S+) \s+no-prepend *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} local-as {{ neighbor.local_as }} no-prepend", "compval": "neighbor.local_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "local_as": "{{ as }}", }, }, }, }, { "name": "neighbor.maximum_prefix", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+maximum-prefix \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} maximum-prefix {{ neighbor.maximum_prefix }}", "compval": "neighbor.maximum_prefix", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "maximum_prefix": "{{ num }}", }, }, }, }, { "name": "neighbor.nexthop_self", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+nexthop-self *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} nexthop-self", "compval": "neighbor.nexthop_self", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "nexthop_self": "{{ True }}", }, }, }, }, { "name": "neighbor.override_capability", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+override-capability *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} override-capability", "compval": "neighbor.override_capability", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "override_capability": "{{ True }}", }, }, }, }, + { + "name": "neighbor.peer_group", + "getval": re.compile( + r""" + ^set + \s+protocols + \s+bgp + \s+(?P\d+) + \s+neighbor + \s+(?P
\S+)\s*$""", + re.VERBOSE, + ), + "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }}", + "compval": "neighbor.peer_group", + "result": { + "as_number": "{{ as_num }}", + "neighbor": { + "{{ address }}": { + "address": "{{ address }}", + }, + }, + }, + }, { "name": "neighbor.passive", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+passive *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} passive", "compval": "neighbor.passive", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "passive": "{{ True }}", }, }, }, }, { "name": "neighbor.password", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+password \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} password {{ neighbor.password }}", "compval": "neighbor.password", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "password": "{{ pwd }}", }, }, }, }, { "name": "neighbor.peer_group_name", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+peer-group \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} peer-group {{ neighbor.peer_group_name }}", "compval": "neighbor.peer_group_name", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "peer_group_name": "{{ name }}", }, }, }, }, { "name": "neighbor.port", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+port \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} port {{ neighbor.port }}", "compval": "neighbor.port", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "port": "{{ num|int }}", }, }, }, }, { "name": "neighbor.prefix_list", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+prefix-list \s+(?Pexport|import) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_prefix_list, "compval": "neighbor.prefix_list", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "prefix_list": [ { "action": "{{ action }}", "prefix_list": "{{ list }}", }, ], }, }, }, }, { "name": "neighbor.remote_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+remote-as \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} remote-as {{ neighbor.remote_as }}", "compval": "neighbor.remote_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "remote_as": "{{ num if num in ['external', 'internal'] else num|int }}", }, }, }, }, { "name": "neighbor.interface.v6only.peer_group", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+interface \s+v6only \s+peer-group \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} interface v6only peer-group {{ neighbor.interface.v6only.peer_group }}", "compval": "neighbor.interface.v6only.peer_group", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "interface": {"v6only": {"peer_group": "{{ pg }}"}}, }, }, }, }, { "name": "neighbor.interface.v6only.remote_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+interface \s+v6only \s+remote-as \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} interface v6only remote-as {{ neighbor.interface.v6only.remote_as }}", "compval": "neighbor.interface.v6only.remote_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "interface": { "v6only": { "remote_as": "{{ num if num in ['external', 'internal'] else num|int }}", }, }, }, }, }, }, { "name": "neighbor.remove_private_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+remote-private-as *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} remote-private-as", "compval": "neighbor.remove_private_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "remove_private_as": "{{ True }}", }, }, }, }, { "name": "neighbor.route_map", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+route-map \s+(?Pexport|import) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_route_map, "compval": "neighbor.route_map", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "route_map": [ { "action": "{{ action }}", "route_map": "{{ map }}", }, ], }, }, }, }, { "name": "neighbor.route_reflector_client", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+route-reflector-client *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} router-reflector-client", "compval": "neighbor.route_reflector_client", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "route_reflector_client": "{{ True }}", }, }, }, }, { "name": "neighbor.route_server_client", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+route-server-client *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} route-server-client", "compval": "neighbor.route_server_client", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "route_server_client": "{{ True }}", }, }, }, }, { "name": "neighbor.shutdown", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+shutdown *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} shutdown", "compval": "neighbor.shutdown", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "shutdown": "{{ True }}", }, }, }, }, { "name": "neighbor.soft_reconfiguration", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+soft-reconfiguration \s+inbound *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} soft-reconfiguration", "compval": "neighbor.soft_reconfiguration", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "soft_reconfiguration": "{{ True }}", }, }, }, }, { "name": "neighbor.strict_capability_match", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+strict-capability-match *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} strict-capability-match", "compval": "neighbor.strict_capability_match", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "strict_capability_match": "{{ True }}", }, }, }, }, { "name": "neighbor.unsuppress_map", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+unsuppress-map \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} unsuppress-map {{ neighbor.unsuppress_map }}", "compval": "neighbor.unsuppress_map", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "unsuppress_map": "{{ map }}", }, }, }, }, { "name": "neighbor.update_source", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+update-source \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} update-source {{ neighbor.update_source }}", "compval": "neighbor.update_source", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "update_source": "{{ src }}", }, }, }, }, { "name": "neighbor.weight", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+weight \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} weight {{ neighbor.weight }}", "compval": "neighbor.weight", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "weight": "{{ num }}", }, }, }, }, { "name": "neighbor.ttl_security", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+ttl-security \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} ttl-security {{ neighbor.ttl_security }}", "compval": "neighbor.ttl_security", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "ttl_security": "{{ ttl|int }}", }, }, }, }, { "name": "neighbor.timers", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+neighbor \s+(?P
\S+) \s+timers \s+(?Pconnect|holdtime|keepalive) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_timers, "remval": "protocols bgp {{ as_number }} neighbor {{ neighbor.address }} timers", "compval": "neighbor.timers", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "timers": { "{{ type }}": "{{ sec }}", }, }, }, }, }, { "name": "timers", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+timers \s+(?P\S+) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_timers, "remval": "protocols bgp {{ as_number }} timers", "compval": "timers", "result": { "as_number": "{{ as_num }}", "timers": { "{{ type }}": "{{ val }}", }, }, }, { "name": "bgp_params.always_compare_med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+always-compare-med *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters always-compare-med", "compval": "bgp_params.always_compare_med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "always_compare_med": "{{ True }}", }, }, }, { "name": "bgp_params.bestpath.as_path", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+bestpath \s+as-path \s+(?Pconfed|ignore|multipath-relax) *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters bestpath as-path {{ bgp_params.bestpath.as_path }}", "compval": "bgp_params.bestpath.as_path", "result": { "as_number": "{{ as_num }}", "bgp_params": { "bestpath": { "as_path": "{{ path }}", }, }, }, }, { "name": "bgp_params.bestpath.compare_routerid", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+bestpath \s+compare-routerid *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters bestpath compare-routerid", "compval": "bgp_params.bestpath.compare_routerid", "result": { "as_number": "{{ as_num }}", "bgp_params": { "bestpath": { "compare_routerid": "{{ True }}", }, }, }, }, { "name": "bgp_params.bestpath.med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+bestpath \s+med \s+(?Pconfed|missing-as-worst) *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters bestpath med {{ bestpath.med }}", "compval": "bgp_params.bestpath.med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "bestpath": { "med": "{{ path }}", }, }, }, }, { "name": "bgp_params.cluster_id", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+cluster-id \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters cluster-id {{ bgp_params.cluster_id }}", "compval": "bgp_params.cluster_id", "result": { "as_number": "{{ as_num }}", "bgp_params": { "cluster_id": "{{ id }}", }, }, }, { "name": "bgp_params.confederation", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+confederation \s+(?Pidentifier|peers) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_params_confederation, "compval": "bgp_params.always_compare_med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "confederation": [ { "peers": "{{ val if type == 'peers' }}", "identifier": "{{ val if type == 'identifier' }}", }, ], }, }, }, { "name": "bgp_params.dampening_half_life", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+dampening \s+half-life \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters dampening half-life {{ bgp_params.dampening.half_life}}", "compval": "bgp_params.dampening.half_life", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "half_life": "{{ val }}", }, }, }, }, { "name": "bgp_params.dampening_max_suppress_time", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+dampening \s+max-suppress-time \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters dampening max-suppress-time {{ bgp_params.dampening.max_suppress_time}}", "compval": "bgp_params.dampening.max_suppress_time", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "max_suppress_time": "{{ val }}", }, }, }, }, { "name": "bgp_params.dampening_re_use", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+dampening \s+re-use \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters dampening re-use {{ bgp_params.dampening.re_use}}", "compval": "bgp_params.dampening.re_use", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "re_use": "{{ val }}", }, }, }, }, { "name": "bgp_params.dampening_start_suppress_time", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+dampening \s+start-suppress-time \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters dampening start-suppress-time {{ bgp_params.dampening.start_suppress_time}}", "compval": "bgp_params.dampening.start_suppress_time", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "start_suppress_time": "{{ val }}", }, }, }, }, { "name": "bgp_params.default", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+default \s*(?Pno-ipv4-unicast)? \s*(?Plocal-pref\s\S+)?\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_params_default, "remval": "protocols bgp {{ as_number }} parameters default", "compval": "bgp_params.default", "result": { "as_number": "{{ as_num }}", "bgp_params": { "default": { "no_ipv4_unicast": "{{ True if no_ipv4_unicast is defined }}", "local_pref": "{{ local_pref.split(" " )[1] if local_pref is defined }}", }, }, }, }, { "name": "bgp_params.deterministic_med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+deterministic-med *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters deterministic-med", "compval": "bgp_params.deterministic_med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "deterministic_med": "{{ True }}", }, }, }, { "name": "bgp_params.disbale_network_import_check", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+disable-network-import-check *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters disable-network-import-check", "compval": "bgp_params.disable_network_import_check", "result": { "as_number": "{{ as_num }}", "bgp_params": { "disable_network_import_check": "{{ True }}", }, }, }, { "name": "bgp_params.distance.prefix", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+distance\sprefix \s+(?P\S+) \s+distance \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters distance prefix {{ bgp_params.distance.prefix }} distance {{ bgp_params.distance.value }}", "compval": "bgp_params.distance.prefix", "remval": "protocols bgp {{ as_number }} parameters distance prefix", "result": { "as_number": "{{ as_num }}", "bgp_params": { "distance": [ { "prefix": "{{ prefix }}", "value": "{{ val }}", }, ], }, }, }, { "name": "bgp_params.distance.global", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+distance\sglobal \s+(?P\S+) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_params_distance, "remval": "protocols bgp {{ as_number }} parameters distance global", "compval": "bgp_params.distance", "result": { "as_number": "{{ as_num }}", "bgp_params": { "distance": [ { "type": "{{ type }}", "value": "{{ val }}", }, ], }, }, }, { "name": "bgp_params.enforce_first_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+enforce-first-as *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters enforce-first-as", "compval": "bgp_params.enforce_first_as", "result": { "as_number": "{{ as_num }}", "bgp_params": { "enforce_first_as": "{{ True }}", }, }, }, { "name": "bgp_params.graceful_restart", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+graceful-restart\s+stalepath-time \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters graceful-restart stalepath-time {{ bgp_params.graceful_restart }}", "compval": "bgp_params.graceful_restart", "result": { "as_number": "{{ as_num }}", "bgp_params": { "graceful_restart": "{{ val }}", }, }, }, { "name": "bgp_params.log_neighbor_changes", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+log-neighbor-changes *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters log-neighbor-changes", "compval": "bgp_params.log_neighbor_changes", "result": { "as_number": "{{ as_num }}", "bgp_params": { "log_neighbor_changes": "{{ True }}", }, }, }, { "name": "bgp_params.no_client_to_client_reflection", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+no-client-to-client-reflection *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters no-client-to-client-reflection", "compval": "bgp_params.log_neighbor_changes", "result": { "as_number": "{{ as_num }}", "bgp_params": { "no_client_to_client_reflection": "{{ True }}", }, }, }, { "name": "bgp_params.no_fast_external_failover", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+no-fast-external-failover *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters no-fast-external-failover", "compval": "bgp_params.no_fast_external_failover", "result": { "as_number": "{{ as_num }}", "bgp_params": { "no_fast_external_failover": "{{ True }}", }, }, }, { "name": "bgp_params.routerid", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+router-id \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters router-id {{ bgp_params.router_id }}", "compval": "bgp_params.router_id", "result": { "as_number": "{{ as_num }}", "bgp_params": { "router_id": "{{ id }}", }, }, }, { "name": "bgp_params.scan_time", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+(?P\d+) \s+parameters \s+scan-time \s+(?P\d+) *$""", re.VERBOSE, ), "setval": "protocols bgp {{ as_number }} parameters scan-time {{ bgp_params.scan_time }}", "compval": "bgp_params.scan_time", "result": { "as_number": "{{ as_num }}", "bgp_params": { "scan_time": "{{ val }}", }, }, }, ] # fmt: on diff --git a/plugins/module_utils/network/vyos/rm_templates/bgp_global_14.py b/plugins/module_utils/network/vyos/rm_templates/bgp_global_14.py index 99be474e..e3383d63 100644 --- a/plugins/module_utils/network/vyos/rm_templates/bgp_global_14.py +++ b/plugins/module_utils/network/vyos/rm_templates/bgp_global_14.py @@ -1,1819 +1,1840 @@ # -*- coding: utf-8 -*- # Copyright 2021 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type """ The Bgp_global parser templates file. This contains a list of parser definitions and associated functions that facilitates both facts gathering and native command generation for the given network resource. """ import re from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.network_template import ( NetworkTemplate, ) def _tmplt_bgp_params_confederation(config_data): command = [] for list_el in config_data["bgp_params"]["confederation"]: for k, v in list_el.items(): command.append( "protocols bgp parameters confederation ".format(**config_data) + k + " " + str(v), ) return command def _tmplt_bgp_maximum_paths(config_data): command = [] for list_el in config_data["maximum_paths"]: command.append( "protocols bgp maximum-paths ".format(**config_data) + list_el["path"] + " " + str(list_el["count"]), ) return command def _tmplt_delete_bgp_maximum_paths(config_data): command = "protocols bgp maximum-paths".format(**config_data) return command def _tmplt_bgp_params_default(config_data): command = "protocols bgp parameters default".format(**config_data) if config_data["bgp_params"]["default"].get("local_pref"): command += " local-pref {local_pref}".format(**config_data["bgp_params"]["default"]) return command def _tmplt_bgp_neighbor_timers(config_data): command = [] for k, v in config_data["neighbor"]["timers"].items(): command.append( "protocols bgp neighbor ".format(**config_data) + config_data["neighbor"]["address"] + " timers " + k + " " + str(v), ) return command def _tmplt_bgp_timers(config_data): command = [] for k, v in config_data["timers"].items(): command.append( "protocols bgp ".format(**config_data) + "timers " + k + " " + str(v), ) return command def _tmplt_bgp_neighbor_attribute_unchanged_as_path(config_data): command = "protocols bgp ".format( **config_data, ) + "neighbor {address} attribute-unchanged as-path".format(**config_data["neighbor"]) return command def _tmplt_bgp_neighbor_attribute_unchanged_med(config_data): command = "protocols bgp ".format( **config_data, ) + "neighbor {address} attribute-unchanged med".format(**config_data["neighbor"]) return command def _tmplt_bgp_neighbor_attribute_unchanged_next_hop(config_data): command = "protocols bgp ".format( **config_data, ) + "neighbor {address} attribute-unchanged next-hop".format(**config_data["neighbor"]) return command def _tmplt_bgp_neighbor_distribute_list(config_data): command = [] for list_el in config_data["neighbor"]["distribute_list"]: command.append( "protocols bgp ".format(**config_data) + "neighbor {address} distribute-list ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["acl"]), ) return command def _tmplt_bgp_neighbor_route_map(config_data): command = [] for list_el in config_data["neighbor"]["route_map"]: command.append( "protocols bgp ".format(**config_data) + "neighbor {address} route-map ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["route_map"]), ) return command def _tmplt_bgp_neighbor_prefix_list(config_data): command = [] for list_el in config_data["neighbor"]["prefix_list"]: command.append( "protocols bgp ".format(**config_data) + "neighbor {address} prefix-list ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["prefix_list"]), ) return command def _tmplt_bgp_neighbor_filter_list(config_data): command = [] for list_el in config_data["neighbor"]["filter_list"]: command.append( "protocols bgp ".format(**config_data) + "neighbor {address} filter-list ".format(**config_data["neighbor"]) + list_el["action"] + " " + str(list_el["path_list"]), ) return command def _tmplt_bgp_params_distance(config_data): command = ( "protocols bgp parameters distance global ".format(**config_data) + config_data["bgp_params"]["distance"]["type"] + " " + str(config_data["bgp_params"]["distance"]["value"]) ) return command class Bgp_globalTemplate14(NetworkTemplate): def __init__(self, lines=None, module=None): prefix = {"set": "set", "remove": "delete"} super(Bgp_globalTemplate14, self).__init__( lines=lines, tmplt=self, prefix=prefix, module=module, ) # fmt: off PARSERS = [ { "name": "router", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s*system-as \s+(?P\d+) *$""", re.VERBOSE, ), "setval": "protocols bgp system-as {{ as_number }}", "remval": "protocols bgp", "compval": "as_number", "result": { "as_number": "{{ as_num }}", }, }, { "name": "maximum_paths", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+maximum-paths \s+(?Pebgp|ibgp) \s+(?P\d+) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_maximum_paths, "remval": _tmplt_delete_bgp_maximum_paths, "compval": "maximum_paths", "result": { "as_number": "{{ as_num }}", "maximum_paths": [ { "path": "{{ path }}", "count": "{{ count }}", }, ], }, }, { "name": "neighbor.advertisement_interval", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+advertisement-interval \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} advertisement-interval {{ neighbor.advertisement_interval }}", "remval": "protocols bgp neighbor {{ neighbor.address }} advertisement-interval", "compval": "neighbor.advertisement_interval", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "advertisement_interval": "{{ interval }}", }, }, }, }, { "name": "neighbor.allowas_in", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+allowas-in \s+number \s+(?P\'\d+\') *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} allowas-in number {{ neighbor.allowas_in }}", "compval": "neighbor.allowas_in", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "allowas_in": "{{ count }}", }, }, }, }, { "name": "neighbor.as_override", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+as-override *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} as-override", "compval": "neighbor.as_override", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "as_override": "{{ True }}", }, }, }, }, { "name": "neighbor.attribute_unchanged.as_path", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+attribute-unchanged \s+(?Pas-path) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_attribute_unchanged_as_path, "compval": "neighbor.attribute_unchanged", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "attribute_unchanged": { "{{ 'as_path' }}": "{{ True }}", }, }, }, }, }, { "name": "neighbor.attribute_unchanged.med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+attribute-unchanged \s+(?Pmed) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_attribute_unchanged_med, "compval": "neighbor.attribute_unchanged", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "attribute_unchanged": { "{{ 'med' }}": "{{ True }}", }, }, }, }, }, { "name": "neighbor.attribute_unchanged.next_hop", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+attribute-unchanged \s+(?Pnext-hop) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_attribute_unchanged_next_hop, "compval": "neighbor.attribute_unchanged", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "attribute_unchanged": { "{{ 'next_hop' }}": "{{ True }}", }, }, }, }, }, { "name": "neighbor.capability_dynamic", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+capability \s+(?Pdynamic) *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} capability dynamic", "compval": "neighbor.capability.dynamic", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "capability": { "dynamic": "{{ True if dynamic is defined}}", }, }, }, }, }, { "name": "neighbor.capability_orf", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+capability \s+orf \s+prefix-list \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} capability orf prefix-list {{ neighbor.capability.orf }}", "compval": "neighbor.capability.orf", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "capability": { "orf": "{{ orf }}", }, }, }, }, }, { "name": "neighbor.default_originate", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+default-originate \s+route-map \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} default-originate route-map {{ neighbor.default_originate }}", "compval": "neighbor.default_originate", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "default_originate": "{{ map }}", }, }, }, }, { "name": "neighbor.description", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+description \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} description {{ neighbor.description }}", "compval": "neighbor.description", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "description": "{{ desc }}", }, }, }, }, { "name": "neighbor.disable_capability_negotiation", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+disable-capability-negotiation *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} disable-capability-negotiation", "compval": "neighbor.disable_capability_negotiation", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "disable_capability_negotiation": "{{ True }}", }, }, }, }, { "name": "neighbor.disable_connected_check", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+disable-connected-check *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} disable-connected-check", "compval": "neighbor.disable_connected_check", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "disable_connected_check": "{{ True }}", }, }, }, }, { "name": "neighbor.disable_send_community", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+disable-send-community \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} disable-send-community {{ neighbor.disable_send_community }}", "compval": "neighbor.disable_send_community", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "disable_send_community": "{{ comm }}", }, }, }, }, { "name": "neighbor.distribute_list", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+distribute-list \s+(?Pexport|import) \s+(?P\d+) *$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_distribute_list, "compval": "neighbor.distribute_list", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "distribute_list": [ { "action": "{{ action }}", "acl": "{{ list }}", }, ], }, }, }, }, { "name": "neighbor.ebgp_multihop", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+ebgp-multihop \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} ebgp-multihop {{ neighbor.ebgp_multihop }}", "compval": "neighbor.ebgp_multihop", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "ebgp_multihop": "{{ hop|int }}", }, }, }, }, { "name": "neighbor.filter_list", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+filter-list \s+(?Pexport|import) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_filter_list, "compval": "neighbor.filter_list", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "filter_list": [ { "action": "{{ action }}", "path_list": "{{ list }}", }, ], }, }, }, }, { "name": "neighbor.local_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+local-as \s+(?P\S+) \s+no-prepend *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} local-as {{ neighbor.local_as }} no-prepend", "compval": "neighbor.local_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "local_as": "{{ as }}", }, }, }, }, { "name": "neighbor.maximum_prefix", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+maximum-prefix \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} maximum-prefix {{ neighbor.maximum_prefix }}", "compval": "neighbor.maximum_prefix", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "maximum_prefix": "{{ num }}", }, }, }, }, { "name": "neighbor.nexthop_self", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+nexthop-self *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} nexthop-self", "compval": "neighbor.nexthop_self", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "nexthop_self": "{{ True }}", }, }, }, }, { "name": "neighbor.override_capability", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+override-capability *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} override-capability", "compval": "neighbor.override_capability", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "override_capability": "{{ True }}", }, }, }, }, + { + "name": "neighbor.peer_group", + "getval": re.compile( + r""" + ^set + \s+protocols + \s+bgp + \s+neighbor + \s+(?P
\S+)\s*$""", + re.VERBOSE, + ), + "setval": "protocols bgp neighbor {{ neighbor.address }}", + "compval": "neighbor.peer_group", + "result": { + "neighbor": { + "{{ address }}": { + "address": "{{ address }}", + }, + }, + }, + }, { "name": "neighbor.passive", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+passive *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} passive", "compval": "neighbor.passive", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "passive": "{{ True }}", }, }, }, }, { "name": "neighbor.password", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+password \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} password {{ neighbor.password }}", "compval": "neighbor.password", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "password": "{{ pwd }}", }, }, }, }, { "name": "neighbor.peer_group_name", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+peer-group \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} peer-group {{ neighbor.peer_group_name }}", "compval": "neighbor.peer_group_name", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "peer_group_name": "{{ name }}", }, }, }, }, { "name": "neighbor.port", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+port \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} port {{ neighbor.port }}", "compval": "neighbor.port", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "port": "{{ num|int }}", }, }, }, }, { "name": "neighbor.prefix_list", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+prefix-list \s+(?Pexport|import) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_prefix_list, "compval": "neighbor.prefix_list", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "prefix_list": [ { "action": "{{ action }}", "prefix_list": "{{ list }}", }, ], }, }, }, }, { "name": "neighbor.remote_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+remote-as \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} remote-as {{ neighbor.remote_as }}", "compval": "neighbor.remote_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "remote_as": "{{ num if num in ['external', 'internal'] else num|int }}", }, }, }, }, { "name": "neighbor.interface.v6only.peer_group", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+interface \s+v6only \s+peer-group \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} interface v6only peer-group {{ neighbor.interface.v6only.peer_group }}", "compval": "neighbor.interface.v6only.peer_group", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "interface": {"v6only": {"peer_group": "{{ pg }}"}}, }, }, }, }, { "name": "neighbor.interface.v6only.remote_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+interface \s+v6only \s+remote-as \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} interface v6only remote-as {{ neighbor.interface.v6only.remote_as }}", "compval": "neighbor.interface.v6only.remote_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "interface": { "v6only": { "remote_as": "{{ num if num in ['external', 'internal'] else num|int }}", }, }, }, }, }, }, { "name": "neighbor.remove_private_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+remote-private-as *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} remote-private-as", "compval": "neighbor.remove_private_as", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "remove_private_as": "{{ True }}", }, }, }, }, { "name": "neighbor.route_map", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+route-map \s+(?Pexport|import) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_route_map, "compval": "neighbor.route_map", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "route_map": [ { "action": "{{ action }}", "route_map": "{{ map }}", }, ], }, }, }, }, { "name": "neighbor.route_reflector_client", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+route-reflector-client *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} router-reflector-client", "compval": "neighbor.route_reflector_client", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "route_reflector_client": "{{ True }}", }, }, }, }, { "name": "neighbor.route_server_client", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+route-server-client *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} route-server-client", "compval": "neighbor.route_server_client", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "route_server_client": "{{ True }}", }, }, }, }, { "name": "neighbor.shutdown", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+shutdown *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} shutdown", "compval": "neighbor.shutdown", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "shutdown": "{{ True }}", }, }, }, }, { "name": "neighbor.soft_reconfiguration", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+soft-reconfiguration \s+inbound *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} soft-reconfiguration", "compval": "neighbor.soft_reconfiguration", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "soft_reconfiguration": "{{ True }}", }, }, }, }, { "name": "neighbor.strict_capability_match", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+strict-capability-match *$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} strict-capability-match", "compval": "neighbor.strict_capability_match", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "strict_capability_match": "{{ True }}", }, }, }, }, { "name": "neighbor.unsuppress_map", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+unsuppress-map \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} unsuppress-map {{ neighbor.unsuppress_map }}", "compval": "neighbor.unsuppress_map", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "unsuppress_map": "{{ map }}", }, }, }, }, { "name": "neighbor.update_source", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+update-source \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} update-source {{ neighbor.update_source }}", "compval": "neighbor.update_source", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "update_source": "{{ src }}", }, }, }, }, { "name": "neighbor.weight", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+weight \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} weight {{ neighbor.weight }}", "compval": "neighbor.weight", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "weight": "{{ num }}", }, }, }, }, { "name": "neighbor.ttl_security", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+ttl-security \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp neighbor {{ neighbor.address }} ttl-security {{ neighbor.ttl_security }}", "compval": "neighbor.ttl_security", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "ttl_security": "{{ ttl|int }}", }, }, }, }, { "name": "neighbor.timers", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+neighbor \s+(?P
\S+) \s+timers \s+(?Pconnect|holdtime|keepalive) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_neighbor_timers, "remval": "protocols bgp neighbor {{ neighbor.address }} timers", "compval": "neighbor.timers", "result": { "as_number": "{{ as_num }}", "neighbor": { "{{ address }}": { "address": "{{ address }}", "timers": { "{{ type }}": "{{ sec }}", }, }, }, }, }, { "name": "timers", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+timers \s+(?P\S+) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_timers, "remval": "protocols bgp timers", "compval": "timers", "result": { "as_number": "{{ as_num }}", "timers": { "{{ type }}": "{{ val }}", }, }, }, { "name": "bgp_params.always_compare_med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+always-compare-med *$""", re.VERBOSE, ), "setval": "protocols bgp parameters always-compare-med", "compval": "bgp_params.always_compare_med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "always_compare_med": "{{ True }}", }, }, }, { "name": "bgp_params.bestpath.as_path", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+bestpath \s+as-path \s+(?Pconfed|ignore|multipath-relax) *$""", re.VERBOSE, ), "setval": "protocols bgp parameters bestpath as-path {{ bgp_params.bestpath.as_path }}", "compval": "bgp_params.bestpath.as_path", "result": { "as_number": "{{ as_num }}", "bgp_params": { "bestpath": { "as_path": "{{ path }}", }, }, }, }, { "name": "bgp_params.bestpath.compare_routerid", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+bestpath \s+compare-routerid *$""", re.VERBOSE, ), "setval": "protocols bgp parameters bestpath compare-routerid", "compval": "bgp_params.bestpath.compare_routerid", "result": { "as_number": "{{ as_num }}", "bgp_params": { "bestpath": { "compare_routerid": "{{ True }}", }, }, }, }, { "name": "bgp_params.bestpath.med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+bestpath \s+med \s+(?Pconfed|missing-as-worst) *$""", re.VERBOSE, ), "setval": "protocols bgp parameters bestpath med {{ bestpath.med }}", "compval": "bgp_params.bestpath.med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "bestpath": { "med": "{{ path }}", }, }, }, }, { "name": "bgp_params.cluster_id", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+cluster-id \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters cluster-id {{ bgp_params.cluster_id }}", "compval": "bgp_params.cluster_id", "result": { "as_number": "{{ as_num }}", "bgp_params": { "cluster_id": "{{ id }}", }, }, }, { "name": "bgp_params.confederation", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+confederation \s+(?Pidentifier|peers) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_params_confederation, "compval": "bgp_params.confederation", "result": { "as_number": "{{ as_num }}", "bgp_params": { "confederation": [ { "peers": "{{ val if type == 'peers' }}", "identifier": "{{ val if type == 'identifier' }}", }, ], }, }, }, { "name": "bgp_params.dampening_half_life", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+dampening \s+half-life \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters dampening half-life {{ bgp_params.dampening.half_life}}", "compval": "bgp_params.dampening.half_life", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "half_life": "{{ val }}", }, }, }, }, { "name": "bgp_params.dampening_max_suppress_time", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+dampening \s+max-suppress-time \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters dampening max-suppress-time {{ bgp_params.dampening.max_suppress_time}}", "compval": "bgp_params.dampening.max_suppress_time", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "max_suppress_time": "{{ val }}", }, }, }, }, { "name": "bgp_params.dampening_re_use", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+dampening \s+re-use \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters dampening re-use {{ bgp_params.dampening.re_use}}", "compval": "bgp_params.dampening.re_use", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "re_use": "{{ val }}", }, }, }, }, { "name": "bgp_params.dampening_start_suppress_time", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+dampening \s+start-suppress-time \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters dampening start-suppress-time {{ bgp_params.dampening.start_suppress_time}}", "compval": "bgp_params.dampening.start_suppress_time", "result": { "as_number": "{{ as_num }}", "bgp_params": { "dampening": { "start_suppress_time": "{{ val }}", }, }, }, }, { "name": "bgp_params.default", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+default \s*(?Plocal-pref\s\S+)?\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_params_default, "remval": "protocols bgp parameters default", "compval": "bgp_params.default", "result": { "as_number": "{{ as_num }}", "bgp_params": { "default": { "local_pref": "{{ local_pref.split(" " )[1] if local_pref is defined }}", }, }, }, }, { "name": "bgp_params.deterministic_med", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+deterministic-med *$""", re.VERBOSE, ), "setval": "protocols bgp parameters deterministic-med", "compval": "bgp_params.deterministic_med", "result": { "as_number": "{{ as_num }}", "bgp_params": { "deterministic_med": "{{ True }}", }, }, }, { "name": "bgp_params.disbale_network_import_check", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+disable-network-import-check *$""", re.VERBOSE, ), "setval": "protocols bgp parameters disable-network-import-check", "compval": "bgp_params.disable_network_import_check", "result": { "as_number": "{{ as_num }}", "bgp_params": { "disable_network_import_check": "{{ True }}", }, }, }, { "name": "bgp_params.distance.prefix", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+distance\sprefix \s+(?P\S+) \s+distance \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters distance prefix {{ bgp_params.distance.prefix }} distance {{ bgp_params.distance.value }}", "compval": "bgp_params.distance.prefix", "remval": "protocols bgp parameters distance prefix", "result": { "as_number": "{{ as_num }}", "bgp_params": { "distance": [ { "prefix": "{{ prefix }}", "value": "{{ val }}", }, ], }, }, }, { "name": "bgp_params.distance.global", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+distance\sglobal \s+(?P\S+) \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": _tmplt_bgp_params_distance, "remval": "protocols bgp parameters distance global", "compval": "bgp_params.distance", "result": { "as_number": "{{ as_num }}", "bgp_params": { "distance": [ { "type": "{{ type }}", "value": "{{ val }}", }, ], }, }, }, { "name": "bgp_params.enforce_first_as", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+enforce-first-as *$""", re.VERBOSE, ), "setval": "protocols bgp parameters enforce-first-as", "compval": "bgp_params.enforce_first_as", "result": { "as_number": "{{ as_num }}", "bgp_params": { "enforce_first_as": "{{ True }}", }, }, }, { "name": "bgp_params.graceful_restart", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+graceful-restart\s+stalepath-time \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters graceful-restart stalepath-time {{ bgp_params.graceful_restart }}", "compval": "bgp_params.graceful_restart", "result": { "as_number": "{{ as_num }}", "bgp_params": { "graceful_restart": "{{ val }}", }, }, }, { "name": "bgp_params.log_neighbor_changes", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+log-neighbor-changes *$""", re.VERBOSE, ), "setval": "protocols bgp parameters log-neighbor-changes", "compval": "bgp_params.log_neighbor_changes", "result": { "as_number": "{{ as_num }}", "bgp_params": { "log_neighbor_changes": "{{ True }}", }, }, }, { "name": "bgp_params.no_client_to_client_reflection", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+no-client-to-client-reflection *$""", re.VERBOSE, ), "setval": "protocols bgp parameters no-client-to-client-reflection", # "compval": "bgp_params.log_neighbor_changes", "compval": "bgp_params.no_client_to_client_reflection", "result": { "as_number": "{{ as_num }}", "bgp_params": { "no_client_to_client_reflection": "{{ True }}", }, }, }, { "name": "bgp_params.no_fast_external_failover", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+no-fast-external-failover *$""", re.VERBOSE, ), "setval": "protocols bgp parameters no-fast-external-failover", "compval": "bgp_params.no_fast_external_failover", "result": { "as_number": "{{ as_num }}", "bgp_params": { "no_fast_external_failover": "{{ True }}", }, }, }, { "name": "bgp_params.routerid", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+router-id \s+(?P\S+)\s*$""", re.VERBOSE, ), "setval": "protocols bgp parameters router-id {{ bgp_params.router_id }}", "compval": "bgp_params.router_id", "result": { "as_number": "{{ as_num }}", "bgp_params": { "router_id": "{{ id }}", }, }, }, { "name": "bgp_params.scan_time", "getval": re.compile( r""" ^set \s+protocols \s+bgp \s+parameters \s+scan-time \s+(?P\d+) *$""", re.VERBOSE, ), "setval": "protocols bgp parameters scan-time {{ bgp_params.scan_time }}", "compval": "bgp_params.scan_time", "result": { "as_number": "{{ as_num }}", "bgp_params": { "scan_time": "{{ val }}", }, }, }, ] # fmt: on diff --git a/tests/integration/targets/vyos_bgp_global/tests/cli/replaced_af.yaml b/tests/integration/targets/vyos_bgp_global/tests/cli/replaced_af.yaml index 7ba9a504..0458822e 100644 --- a/tests/integration/targets/vyos_bgp_global/tests/cli/replaced_af.yaml +++ b/tests/integration/targets/vyos_bgp_global/tests/cli/replaced_af.yaml @@ -1,72 +1,71 @@ --- - debug: msg: START vyos_bgp_global replaced integration tests on connection={{ ansible_connection }} - include_tasks: _remove_config.yaml - include_tasks: _populate_af.yaml - block: - name: Replace the existing af configuration with the provided running configuration register: result ignore_errors: true vyos.vyos.vyos_bgp_global: config: as_number: "65536" bgp_params: always_compare_med: true dampening: start_suppress_time: 5 max_suppress_time: 20 half_life: 33 re_use: 60 bestpath: as_path: confed compare_routerid: true neighbor: - address: 192.0.2.43 disable_connected_check: true advertisement_interval: 72 capability: dynamic: true timers: holdtime: 30 keepalive: 10 remote_as: 102 - address: 203.0.113.0 capability: dynamic: true remote_as: 102 state: replaced - assert: that: - result.msg == 'Use the _bgp_address_family module to delete the address_family under neighbor 5001::64, before replacing/deleting the neighbor.' - name: Peer group with an address family (1.4 and later) when: vyos_version is version('1.4.0', '>=', version_type='semver') block: - name: Add a peer group with an address family vyos.vyos.vyos_config: lines: - set protocols bgp peer-group RR-CLIENTS remote-as '65536' - set protocols bgp peer-group RR-CLIENTS address-family 'ipv4-unicast' vars: ansible_connection: ansible.netcommon.network_cli - name: Replace without the peer group that has an address family register: result ignore_errors: true vyos.vyos.vyos_bgp_global: config: as_number: "65536" neighbor: - address: 5001::64 state: replaced - assert: that: - - result.msg == 'Use the _bgp_address_family module to delete the address_family under neighbor RR-CLIENTS, before replacing/deleting the neighbor.' - + - "result.msg == 'Remove the address-family settings of peer-group RR-CLIENTS with vyos_config before replacing/deleting the peer group: vyos_bgp_address_family does not manage peer groups.'" always: - include_tasks: _remove_config.yaml diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_multipath_relax_config.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_multipath_relax_config.cfg new file mode 100644 index 00000000..2ab5f059 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_multipath_relax_config.cfg @@ -0,0 +1 @@ +set protocols bgp 65536 parameters bestpath as-path multipath-relax diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_multipath_relax_config_14.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_multipath_relax_config_14.cfg new file mode 100644 index 00000000..bf9d2df9 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_multipath_relax_config_14.cfg @@ -0,0 +1,2 @@ +set protocols bgp system-as 65536 +set protocols bgp parameters bestpath as-path multipath-relax diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_remote_as_config.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_remote_as_config.cfg new file mode 100644 index 00000000..303ab6c2 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_remote_as_config.cfg @@ -0,0 +1 @@ +set protocols bgp 65536 neighbor 192.0.2.1 remote-as external diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_remote_as_config_14.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_remote_as_config_14.cfg new file mode 100644 index 00000000..fa4c56fb --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_remote_as_config_14.cfg @@ -0,0 +1,3 @@ +set protocols bgp system-as 65536 +set protocols bgp neighbor 192.0.2.1 remote-as external +set protocols bgp neighbor 192.0.2.2 remote-as 65002 diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_v6only_config.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_v6only_config.cfg new file mode 100644 index 00000000..c9060a13 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_parsed_v6only_config.cfg @@ -0,0 +1 @@ +set protocols bgp 65536 neighbor eth1 interface v6only remote-as external diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_peer_group_bare_config_14.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_peer_group_bare_config_14.cfg new file mode 100644 index 00000000..535364b5 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_peer_group_bare_config_14.cfg @@ -0,0 +1,5 @@ +set protocols bgp system-as '65001' +set protocols bgp neighbor 192.0.2.1 peer-group 'RR-CLIENTS' +set protocols bgp peer-group AFONLY address-family 'ipv4-unicast' +set protocols bgp peer-group BARE +set protocols bgp peer-group RR-CLIENTS remote-as '65001' diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_peer_group_same_name_config_14.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_peer_group_same_name_config_14.cfg new file mode 100644 index 00000000..9e73c517 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_bgp_global_peer_group_same_name_config_14.cfg @@ -0,0 +1,4 @@ +set protocols bgp system-as '65001' +set protocols bgp neighbor eth1 address-family ipv6-unicast +set protocols bgp neighbor eth1 interface v6only remote-as 'external' +set protocols bgp peer-group eth1 remote-as 'external' diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_vrf_bgp_af_config.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_vrf_bgp_af_config.cfg new file mode 100644 index 00000000..73f82ea7 --- /dev/null +++ b/tests/unit/modules/network/vyos/fixtures/vyos_vrf_bgp_af_config.cfg @@ -0,0 +1,2 @@ +set protocols bgp neighbor 1.1.1.3 address-family ipv4-unicast +set vrf name vrf-red protocols bgp neighbor 192.0.2.1 address-family ipv4-unicast diff --git a/tests/unit/modules/network/vyos/test_vyos_bgp_global.py b/tests/unit/modules/network/vyos/test_vyos_bgp_global.py index c1549492..5127a8c4 100644 --- a/tests/unit/modules/network/vyos/test_vyos_bgp_global.py +++ b/tests/unit/modules/network/vyos/test_vyos_bgp_global.py @@ -1,529 +1,529 @@ # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # Make coding more python3-ish from __future__ import absolute_import, division, print_function __metaclass__ = type from unittest.mock import patch from ansible_collections.vyos.vyos.plugins.modules import vyos_bgp_global from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args from .vyos_module import TestVyosModule, load_fixture class TestVyosBgpglobalModule(TestVyosModule): module = vyos_bgp_global def setUp(self): super(TestVyosBgpglobalModule, self).setUp() self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_execute_show_command_config = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global.bgp_global.Bgp_global._get_config", ) self.execute_show_command_config = self.mock_execute_show_command_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_execute_show_command = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.bgp_global.bgp_global.Bgp_globalFacts.get_device_data", ) self.execute_show_command = self.mock_execute_show_command.start() self.mock_get_os_version = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global.bgp_global.get_os_version", ) self.test_version = "1.2" self.get_os_version = self.mock_get_os_version.start() self.get_os_version.return_value = self.test_version self.mock_facts_get_os_version = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.bgp_global.bgp_global.get_os_version", ) self.get_facts_os_version = self.mock_facts_get_os_version.start() self.get_facts_os_version.return_value = self.test_version self.maxDiff = None def tearDown(self): super(TestVyosBgpglobalModule, self).tearDown() self.mock_get_resource_connection_config.stop() self.mock_get_resource_connection_facts.stop() self.mock_execute_show_command.stop() self.mock_execute_show_command_config.stop() self.mock_get_os_version.stop() self.mock_facts_get_os_version.stop() def load_fixtures(self, commands=None, filename=None): if filename is None: filename = "vyos_bgp_global_config.cfg" def load_from_file(*args, **kwargs): output = load_fixture(filename) return output self.execute_show_command.side_effect = load_from_file self.execute_show_command_config.side_effect = load_from_file def test_vyos_bgp_global_merged_idempotent(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="10.0.0.4", disable_connected_check=True, timers=dict(holdtime=30, keepalive=10), ), dict( address="192.168.0.2", ebgp_multihop=2, remote_as="65535", update_source="192.168.0.1", ), dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], # network=[ # dict(address="172.16.42.32/27", backdoor=True), # dict(address="172.16.42.251/32", route_map="map01"), # ], bgp_params=dict( bestpath=dict(as_path="confed", compare_routerid=True), default=dict(no_ipv4_unicast=True), router_id="10.1.1.1", ), # redistribute=[ # dict(protocol="kernel", route_map="map01"), # dict(protocol="static", metric=20), # dict(protocol="static", route_map="map01"), # ], ), state="merged", ), ) self.execute_module(changed=False, commands=[]) def test_vyos_bgp_global_merged(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], bgp_params=dict( confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="merged", ), ) commands = [ "set protocols bgp 65536 parameters confederation peers 20", "set protocols bgp 65536 parameters confederation identifier 66", ] self.execute_module(changed=True, commands=commands) def test_vyos_bgp_global_replaced_idempotent(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="10.0.0.4", disable_connected_check=True, timers=dict(holdtime=30, keepalive=10), ), dict( address="192.168.0.2", ebgp_multihop=2, remote_as="65535", update_source="192.168.0.1", ), dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], # network=[ # dict(address="172.16.42.32/27", backdoor=True), # dict(address="172.16.42.251/32", route_map="map01"), # ], bgp_params=dict( bestpath=dict(as_path="confed", compare_routerid=True), default=dict(no_ipv4_unicast=True), router_id="10.1.1.1", ), # redistribute=[ # dict(protocol="kernel", route_map="map01"), # dict(protocol="static", metric=20), # dict(protocol="static", route_map="map01"), # ], ), state="replaced", ), ) self.execute_module(changed=False, commands=[]) # def test_vyos_bgp_global_replaced(self): set_module_args( dict( config=dict( as_number="65536", timers=dict(holdtime=30, keepalive=10), neighbor=[ dict( address="200.11.155.3", ), dict( address="2001:db8::2", remote_as="65535", default_originate="map01", ), ], bgp_params=dict( log_neighbor_changes=True, no_client_to_client_reflection=True, confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="replaced", ), ) commands = [ "delete protocols bgp 65536 parameters default", "delete protocols bgp 65536 parameters bestpath compare-routerid", "delete protocols bgp 65536 parameters bestpath as-path confed", # "delete protocols bgp 65536 network", # "delete protocols bgp 65536 redistribute", "delete protocols bgp 65536 neighbor 2001:db8::2 update-source 2001:db8::1", "delete protocols bgp 65536 neighbor 2001:db8::2 ebgp-multihop 2", "delete protocols bgp 65536 neighbor 192.168.0.2", "delete protocols bgp 65536 neighbor 10.0.0.4", "set protocols bgp 65536 parameters log-neighbor-changes", "set protocols bgp 65536 parameters no-client-to-client-reflection", "set protocols bgp 65536 parameters confederation peers 20", "set protocols bgp 65536 parameters confederation identifier 66", "set protocols bgp 65536 timers holdtime 30", "set protocols bgp 65536 timers keepalive 10", ] self.execute_module(changed=True, commands=commands) # def test_vyos_bgp_global_purged(self): set_module_args(dict(config=dict(as_number="65536"), state="purged")) # commands = ["delete protocols bgp 65536"] self.execute_module(changed=True, commands=commands) # def test_vyos_bgp_global_incorrect_instance(self): set_module_args( dict( config=dict( as_number="100", timers=dict(holdtime=30, keepalive=10), neighbor=[ dict( address="200.11.155.3", ), dict( address="2001:db8::2", remote_as="65535", default_originate="map01", ), ], bgp_params=dict( log_neighbor_changes=True, no_client_to_client_reflection=True, confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="replaced", ), ) result = self.execute_module(failed=True) self.assertIn("Only one bgp instance is allowed per device", result["msg"]) def test_vyos_bgp_global_replaced_af(self): set_module_args( dict( config=dict( as_number="65536", timers=dict(holdtime=30, keepalive=10), neighbor=[ dict( address="200.11.155.3", ), dict( address="2001:db8::2", remote_as="65535", default_originate="map01", ), ], bgp_params=dict( log_neighbor_changes=True, no_client_to_client_reflection=True, confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="replaced", ), ) result = self.execute_module(failed=True, filename="vyos_bgp_global_af_config.cfg") self.assertIn( "Use the _bgp_address_family module to delete the address_family under neighbor 5001::64, before replacing/deleting the neighbor.", result["msg"], ) def test_vyos_bgp_global_rendered(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="10.0.0.4", disable_connected_check=True, timers=dict(holdtime=30, keepalive=10), ), dict( address="192.168.0.2", ebgp_multihop=2, remote_as="65535", update_source="192.168.0.1", ), dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], # network=[ # dict(address="172.16.42.32/27", backdoor=True), # dict(address="172.16.42.251/32", route_map="map01"), # ], bgp_params=dict( bestpath=dict(as_path="confed", compare_routerid=True), default=dict(no_ipv4_unicast=True), router_id="10.1.1.1", ), # redistribute=[ # dict(protocol="kernel", route_map="map01"), # dict(protocol="static", metric=20), # dict(protocol="static", route_map="map01"), # ], ), state="rendered", ), ) rendered_cmds = [ "set protocols bgp 65536 neighbor 10.0.0.4 disable-connected-check", "set protocols bgp 65536 neighbor 10.0.0.4 timers holdtime 30", "set protocols bgp 65536 neighbor 10.0.0.4 timers keepalive 10", "set protocols bgp 65536 neighbor 192.168.0.2 ebgp-multihop 2", "set protocols bgp 65536 neighbor 192.168.0.2 remote-as 65535", "set protocols bgp 65536 neighbor 192.168.0.2 update-source 192.168.0.1", "set protocols bgp 65536 neighbor 2001:db8::2 ebgp-multihop 2", "set protocols bgp 65536 neighbor 2001:db8::2 remote-as 65535", "set protocols bgp 65536 neighbor 2001:db8::2 update-source 2001:db8::1", # "set protocols bgp 65536 redistribute kernel route-map map01", # "set protocols bgp 65536 redistribute static route-map map01", # "set protocols bgp 65536 network 172.16.42.32/27 backdoor", # "set protocols bgp 65536 network 172.16.42.251/32 route-map map01", "set protocols bgp 65536 parameters bestpath as-path confed", "set protocols bgp 65536 parameters bestpath compare-routerid", "set protocols bgp 65536 parameters default no-ipv4-unicast", "set protocols bgp 65536 parameters router-id 10.1.1.1", ] result = self.execute_module(changed=False) self.assertEqual( sorted(result["rendered"]), sorted(rendered_cmds), result["rendered"], ) def test_vyos_bgp_global_parsed(self): commands = [ "set protocols bgp 65536 neighbor 10.0.0.4 disable-connected-check", "set protocols bgp 65536 neighbor 10.0.0.4 timers holdtime 30", "set protocols bgp 65536 neighbor 10.0.0.4 timers keepalive 10", "set protocols bgp 65536 neighbor 192.168.0.2 ebgp-multihop 2", "set protocols bgp 65536 neighbor 192.168.0.2 remote-as 65535", "set protocols bgp 65536 neighbor 192.168.0.2 update-source 192.168.0.1", "set protocols bgp 65536 neighbor 2001:db8::2 ebgp-multihop 2", "set protocols bgp 65536 neighbor 2001:db8::2 remote-as 65535", "set protocols bgp 65536 neighbor 2001:db8::2 update-source 2001:db8::1", # "set protocols bgp 65536 redistribute kernel route-map map01", # "set protocols bgp 65536 redistribute static route-map map01", # "set protocols bgp 65536 network 172.16.42.32/27 backdoor", # "set protocols bgp 65536 network 172.16.42.251/32 route-map map01", "set protocols bgp 65536 parameters bestpath as-path confed", "set protocols bgp 65536 parameters bestpath compare-routerid", "set protocols bgp 65536 parameters default no-ipv4-unicast", "set protocols bgp 65536 parameters router-id 10.1.1.1", ] parsed_str = "\n".join(commands) set_module_args(dict(running_config=parsed_str, state="parsed")) result = self.execute_module(changed=False) parsed_list = { "as_number": 65536, "bgp_params": { "bestpath": {"as_path": "confed", "compare_routerid": True}, "default": {"no_ipv4_unicast": True}, "router_id": "10.1.1.1", }, "neighbor": [ { "address": "10.0.0.4", "disable_connected_check": True, "timers": {"holdtime": 30, "keepalive": 10}, }, { "address": "192.168.0.2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "192.168.0.1", }, { "address": "2001:db8::2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "2001:db8::1", }, ], # "network": [ # {"address": "172.16.42.32/27", "backdoor": True}, # {"address": "172.16.42.251/32", "route_map": "map01"}, # ], # "redistribute": [ # {"protocol": "kernel", "route_map": "map01"}, # {"protocol": "static", "route_map": "map01"}, # ], } self.assertEqual(sorted(parsed_list), sorted(result["parsed"])) def test_vyos_bgp_global_gathered(self): set_module_args(dict(state="gathered")) result = self.execute_module(changed=False) gather_list = { "as_number": 65536, "bgp_params": { "bestpath": {"as_path": "confed", "compare_routerid": True}, "default": {"no_ipv4_unicast": True}, "router_id": "10.1.1.1", }, "neighbor": [ { "address": "10.0.0.4", "disable_connected_check": True, "timers": {"holdtime": 30, "keepalive": 10}, }, { "address": "192.168.0.2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "192.168.0.1", }, { "address": "2001:db8::2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "2001:db8::1", }, ], # "network": [ # {"address": "172.16.42.32/27", "backdoor": True}, # {"address": "172.16.42.251/32", "route_map": "map01"}, # ], # "redistribute": [ # {"protocol": "kernel", "route_map": "map01"}, # {"metric": 20, "protocol": "static"}, # {"protocol": "static", "route_map": "map01"}, # ], } self.assertEqual(sorted(gather_list), sorted(result["gathered"])) def test_vyos_bgp_global_bestpath_multipath_relax_parsed(self): set_module_args( dict( - running_config="set protocols bgp 65536 parameters bestpath as-path multipath-relax", + running_config=load_fixture("vyos_bgp_global_parsed_multipath_relax_config.cfg"), state="parsed", ), ) self.assertEqual( self.execute_module(changed=False)["parsed"], {"as_number": 65536, "bgp_params": {"bestpath": {"as_path": "multipath-relax"}}}, ) def test_vyos_bgp_global_remote_as_external_parsed(self): set_module_args( dict( - running_config="set protocols bgp 65536 neighbor 192.0.2.1 remote-as external", + running_config=load_fixture("vyos_bgp_global_parsed_remote_as_config.cfg"), state="parsed", ), ) self.assertEqual( self.execute_module(changed=False)["parsed"], {"as_number": 65536, "neighbor": [{"address": "192.0.2.1", "remote_as": "external"}]}, ) def test_vyos_bgp_global_interface_v6only_parsed(self): set_module_args( dict( - running_config="set protocols bgp 65536 neighbor eth1 interface v6only remote-as external", + running_config=load_fixture("vyos_bgp_global_parsed_v6only_config.cfg"), state="parsed", ), ) self.assertEqual( self.execute_module(changed=False)["parsed"], { "as_number": 65536, "neighbor": [ {"address": "eth1", "interface": {"v6only": {"remote_as": "external"}}}, ], }, ) diff --git a/tests/unit/modules/network/vyos/test_vyos_bgp_global14.py b/tests/unit/modules/network/vyos/test_vyos_bgp_global14.py index d0b7ad00..57917817 100644 --- a/tests/unit/modules/network/vyos/test_vyos_bgp_global14.py +++ b/tests/unit/modules/network/vyos/test_vyos_bgp_global14.py @@ -1,633 +1,867 @@ # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # Make coding more python3-ish from __future__ import absolute_import, division, print_function __metaclass__ = type from unittest.mock import patch from ansible_collections.vyos.vyos.plugins.modules import vyos_bgp_global from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args from .vyos_module import TestVyosModule, load_fixture class TestVyosBgpglobalModule(TestVyosModule): module = vyos_bgp_global def setUp(self): super(TestVyosBgpglobalModule, self).setUp() self.mock_get_resource_connection_config = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", ) self.get_resource_connection_config = self.mock_get_resource_connection_config.start() self.mock_execute_show_command_config = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global.bgp_global.Bgp_global._get_config", ) self.execute_show_command_config = self.mock_execute_show_command_config.start() self.mock_get_resource_connection_facts = patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", ) self.get_resource_connection_facts = self.mock_get_resource_connection_facts.start() self.mock_execute_show_command = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.bgp_global.bgp_global.Bgp_globalFacts.get_device_data", ) self.execute_show_command = self.mock_execute_show_command.start() self.mock_get_os_version = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global.bgp_global.get_os_version", ) self.test_version = "1.4" self.get_os_version = self.mock_get_os_version.start() self.get_os_version.return_value = self.test_version self.mock_facts_get_os_version = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.bgp_global.bgp_global.get_os_version", ) self.get_facts_os_version = self.mock_facts_get_os_version.start() self.get_facts_os_version.return_value = self.test_version self.maxDiff = None def tearDown(self): super(TestVyosBgpglobalModule, self).tearDown() self.mock_get_resource_connection_config.stop() self.mock_get_resource_connection_facts.stop() self.mock_execute_show_command.stop() self.mock_execute_show_command_config.stop() self.mock_get_os_version.stop() self.mock_facts_get_os_version.stop() def load_fixtures(self, commands=None, filename=None): if filename is None: filename = "vyos_bgp_global_config_14.cfg" def load_from_file(*args, **kwargs): output = load_fixture(filename) return output self.execute_show_command.side_effect = load_from_file self.execute_show_command_config.side_effect = load_from_file def test_vyos_bgp_global_merged_idempotent(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="10.0.0.4", disable_connected_check=True, timers=dict(holdtime=30, keepalive=10), ), dict( address="192.168.0.2", ebgp_multihop=2, remote_as="65535", update_source="192.168.0.1", ), dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], bgp_params=dict( bestpath=dict(as_path="confed", compare_routerid=True), default=dict(no_ipv4_unicast=True), router_id="10.1.1.1", ), ), state="merged", ), ) self.execute_module(changed=False, commands=[]) def test_vyos_bgp_global_merged(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], bgp_params=dict( confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="merged", ), ) commands = [ "set protocols bgp parameters confederation peers 20", "set protocols bgp parameters confederation identifier 66", ] self.execute_module(changed=True, commands=commands) def test_vyos_bgp_global_replaced_idempotent(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="10.0.0.4", disable_connected_check=True, timers=dict(holdtime=30, keepalive=10), ), dict( address="192.168.0.2", ebgp_multihop=2, remote_as="65535", update_source="192.168.0.1", ), dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], bgp_params=dict( bestpath=dict(as_path="confed", compare_routerid=True), default=dict(no_ipv4_unicast=True), router_id="10.1.1.1", ), ), state="replaced", ), ) self.execute_module(changed=False, commands=[]) def test_vyos_bgp_global_replaced(self): set_module_args( dict( config=dict( as_number="65536", timers=dict(holdtime=30, keepalive=10), neighbor=[ dict( address="200.11.155.3", ), dict( address="2001:db8::2", remote_as="65535", default_originate="map01", ), ], bgp_params=dict( log_neighbor_changes=True, no_client_to_client_reflection=True, confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="replaced", ), ) commands = [ "delete protocols bgp parameters bestpath compare-routerid", "delete protocols bgp parameters bestpath as-path confed", "delete protocols bgp neighbor 2001:db8::2 update-source 2001:db8::1", "delete protocols bgp neighbor 2001:db8::2 ebgp-multihop 2", "delete protocols bgp neighbor 192.168.0.2", "delete protocols bgp neighbor 10.0.0.4", "set protocols bgp parameters log-neighbor-changes", "set protocols bgp parameters no-client-to-client-reflection", "set protocols bgp parameters confederation peers 20", "set protocols bgp parameters confederation identifier 66", "set protocols bgp timers holdtime 30", "set protocols bgp timers keepalive 10", ] self.execute_module(changed=True, commands=commands) # def test_vyos_bgp_global_purged(self): set_module_args(dict(config=dict(as_number="65536"), state="purged")) # commands = ["delete protocols bgp"] self.execute_module(changed=True, commands=commands) def test_vyos_bgp_global_replaced_af(self): set_module_args( dict( config=dict( as_number="65536", timers=dict(holdtime=30, keepalive=10), neighbor=[ dict( address="200.11.155.3", ), dict( address="2001:db8::2", remote_as="65535", default_originate="map01", ), ], bgp_params=dict( log_neighbor_changes=True, no_client_to_client_reflection=True, confederation=[dict(peers=20), dict(identifier=66)], router_id="10.1.1.1", ), ), state="replaced", ), ) result = self.execute_module(failed=True, filename="vyos_bgp_global_af_config_14.cfg") self.assertIn( "Use the _bgp_address_family module to delete the address_family under neighbor 5001::64, before replacing/deleting the neighbor.", result["msg"], ) def test_vyos_bgp_global_missing_as_number(self): set_module_args( dict( config=dict(neighbor=[dict(address="192.0.2.1", remote_as=65002)]), state="merged", ), ) result = self.execute_module(failed=True) self.assertIn("as_number is required", result["msg"]) def test_vyos_bgp_global_rendered(self): set_module_args( dict( config=dict( as_number="65536", neighbor=[ dict( address="10.0.0.4", disable_connected_check=True, timers=dict(holdtime=30, keepalive=10), ), dict( address="192.168.0.2", ebgp_multihop=2, remote_as="65535", update_source="192.168.0.1", ), dict( address="2001:db8::2", ebgp_multihop=2, remote_as="65535", update_source="2001:db8::1", ), ], bgp_params=dict( bestpath=dict(as_path="confed", compare_routerid=True), default=dict(no_ipv4_unicast=True), router_id="10.1.1.1", ), ), state="rendered", ), ) rendered_cmds = [ "set protocols bgp system-as 65536", "set protocols bgp neighbor 10.0.0.4 disable-connected-check", "set protocols bgp neighbor 10.0.0.4 timers holdtime 30", "set protocols bgp neighbor 10.0.0.4 timers keepalive 10", "set protocols bgp neighbor 192.168.0.2 ebgp-multihop 2", "set protocols bgp neighbor 192.168.0.2 remote-as 65535", "set protocols bgp neighbor 192.168.0.2 update-source 192.168.0.1", "set protocols bgp neighbor 2001:db8::2 ebgp-multihop 2", "set protocols bgp neighbor 2001:db8::2 remote-as 65535", "set protocols bgp neighbor 2001:db8::2 update-source 2001:db8::1", "set protocols bgp parameters bestpath as-path confed", "set protocols bgp parameters bestpath compare-routerid", "set protocols bgp parameters router-id 10.1.1.1", ] result = self.execute_module(changed=False) self.assertEqual( sorted(result["rendered"]), sorted(rendered_cmds), result["rendered"], ) def test_vyos_bgp_global_parsed(self): commands = [ "set protocols bgp system-as 65536", "set protocols bgp neighbor 10.0.0.4 disable-connected-check", "set protocols bgp neighbor 10.0.0.4 timers holdtime 30", "set protocols bgp neighbor 10.0.0.4 timers keepalive 10", "set protocols bgp neighbor 192.168.0.2 ebgp-multihop 2", "set protocols bgp neighbor 192.168.0.2 remote-as 65535", "set protocols bgp neighbor 192.168.0.2 update-source 192.168.0.1", "set protocols bgp neighbor 2001:db8::2 ebgp-multihop 2", "set protocols bgp neighbor 2001:db8::2 remote-as 65535", "set protocols bgp neighbor 2001:db8::2 update-source 2001:db8::1", "set protocols bgp parameters bestpath as-path confed", "set protocols bgp parameters bestpath compare-routerid", "set protocols bgp parameters default no-ipv4-unicast", "set protocols bgp parameters router-id 10.1.1.1", ] parsed_str = "\n".join(commands) set_module_args(dict(running_config=parsed_str, state="parsed")) result = self.execute_module(changed=False) parsed_list = { "as_number": 65536, "bgp_params": { "bestpath": {"as_path": "confed", "compare_routerid": True}, "default": {"no_ipv4_unicast": True}, "router_id": "10.1.1.1", }, "neighbor": [ { "address": "10.0.0.4", "disable_connected_check": True, "timers": {"holdtime": 30, "keepalive": 10}, }, { "address": "192.168.0.2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "192.168.0.1", }, { "address": "2001:db8::2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "2001:db8::1", }, ], } self.assertEqual(sorted(parsed_list), sorted(result["parsed"])) def test_vyos_bgp_global_gathered(self): set_module_args(dict(state="gathered")) result = self.execute_module(changed=False) gather_list = { "as_number": 65536, "bgp_params": { "bestpath": {"as_path": "confed", "compare_routerid": True}, "default": {"no_ipv4_unicast": True}, "router_id": "10.1.1.1", }, "neighbor": [ { "address": "10.0.0.4", "disable_connected_check": True, "timers": {"holdtime": 30, "keepalive": 10}, }, { "address": "192.168.0.2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "192.168.0.1", }, { "address": "2001:db8::2", "ebgp_multihop": 2, "remote_as": 65535, "update_source": "2001:db8::1", }, ], } self.assertEqual(sorted(gather_list), sorted(result["gathered"])) def test_vyos_bgp_global_reflection_flags_independent(self): self.get_os_version.return_value = "1.5" set_module_args( dict( config=dict(as_number=65001, bgp_params=dict(log_neighbor_changes=True)), state="rendered", ), ) cmds = self.execute_module(changed=False)["rendered"] self.assertIn("set protocols bgp parameters log-neighbor-changes", cmds) self.assertFalse(any("no-client-to-client-reflection" in c for c in cmds)) set_module_args( dict( config=dict(as_number=65001, bgp_params=dict(no_client_to_client_reflection=True)), state="rendered", ), ) cmds = self.execute_module(changed=False)["rendered"] self.assertIn("set protocols bgp parameters no-client-to-client-reflection", cmds) self.assertFalse(any("log-neighbor-changes" in c for c in cmds)) def test_vyos_bgp_global_peer_group_rendered(self): self.get_os_version.return_value = "1.5" group = dict(address="RR-CLIENTS", peer_group=True, remote_as=65001, update_source="lo") member = dict(address="192.0.2.1", peer_group_name="RR-CLIENTS") set_module_args( dict(config=dict(as_number=65001, neighbor=[group, member]), state="rendered"), ) self.assertEqual( sorted(self.execute_module(changed=False)["rendered"]), [ "set protocols bgp neighbor 192.0.2.1 peer-group RR-CLIENTS", "set protocols bgp peer-group RR-CLIENTS remote-as 65001", "set protocols bgp peer-group RR-CLIENTS update-source lo", "set protocols bgp system-as 65001", ], ) def test_vyos_bgp_global_peer_group_replaced(self): self.get_os_version.return_value = "1.5" self.get_facts_os_version.return_value = "1.5" group = dict(address="RR-CLIENTS", peer_group=True, remote_as=65001) member = dict(address="192.0.2.1", peer_group_name="RR-CLIENTS") set_module_args( dict(config=dict(as_number=65001, neighbor=[group, member]), state="replaced"), ) self.execute_module( changed=True, commands=["delete protocols bgp peer-group RR-CLIENTS update-source lo"], filename="vyos_bgp_global_peer_group_config_14.cfg", ) def test_vyos_bgp_global_peer_group_af_replaced(self): set_module_args( dict( config=dict( as_number=65001, neighbor=[dict(address="PG1", peer_group=True, remote_as=65001)], ), state="replaced", ), ) result = self.execute_module( failed=True, filename="vyos_bgp_global_peer_group_af_config_14.cfg", ) - self.assertIn("address_family under neighbor PG10", result["msg"]) + self.assertIn("address-family settings of peer-group PG10 with vyos_config", result["msg"]) def test_vyos_bgp_global_peer_group_af_exact_name(self): set_module_args( dict( config=dict( as_number=65001, neighbor=[dict(address="PG10", peer_group=True, remote_as=65001)], ), state="replaced", ), ) self.execute_module( changed=True, commands=["delete protocols bgp peer-group PG1"], filename="vyos_bgp_global_peer_group_af_config_14.cfg", ) def test_vyos_bgp_global_bestpath_multipath_relax_rendered(self): set_module_args( dict( config=dict( as_number=65536, bgp_params=dict(bestpath=dict(as_path="multipath-relax")), ), state="rendered", ), ) self.assertEqual( sorted(self.execute_module(changed=False)["rendered"]), [ "set protocols bgp parameters bestpath as-path multipath-relax", "set protocols bgp system-as 65536", ], ) def test_vyos_bgp_global_bestpath_multipath_relax_parsed(self): set_module_args( dict( - running_config="set protocols bgp system-as 65536\n" - "set protocols bgp parameters bestpath as-path multipath-relax", + running_config=load_fixture("vyos_bgp_global_parsed_multipath_relax_config_14.cfg"), state="parsed", ), ) self.assertEqual( self.execute_module(changed=False)["parsed"], {"as_number": 65536, "bgp_params": {"bestpath": {"as_path": "multipath-relax"}}}, ) def test_vyos_bgp_global_remote_as_external_rendered(self): set_module_args( dict( config=dict( as_number=65536, neighbor=[dict(address="192.0.2.1", remote_as="external")], ), state="rendered", ), ) self.assertEqual( sorted(self.execute_module(changed=False)["rendered"]), [ "set protocols bgp neighbor 192.0.2.1 remote-as external", "set protocols bgp system-as 65536", ], ) def test_vyos_bgp_global_remote_as_external_parsed(self): set_module_args( dict( - running_config="set protocols bgp system-as 65536\n" - "set protocols bgp neighbor 192.0.2.1 remote-as external\n" - "set protocols bgp neighbor 192.0.2.2 remote-as 65002", + running_config=load_fixture("vyos_bgp_global_parsed_remote_as_config_14.cfg"), state="parsed", ), ) self.assertEqual( self.execute_module(changed=False)["parsed"], { "as_number": 65536, "neighbor": [ {"address": "192.0.2.1", "remote_as": "external"}, {"address": "192.0.2.2", "remote_as": 65002}, ], }, ) def test_vyos_bgp_global_bestpath_as_path_change(self): set_module_args( dict( config=dict( as_number=65536, bgp_params=dict(bestpath=dict(as_path="multipath-relax")), ), state="merged", ), ) self.execute_module( changed=True, commands=[ "delete protocols bgp parameters bestpath as-path confed", "set protocols bgp parameters bestpath as-path multipath-relax", ], ) def test_vyos_bgp_global_interface_v6only_rendered(self): set_module_args( dict( config=dict( as_number=65536, neighbor=[ dict( address="eth1", interface=dict( v6only=dict(remote_as="external", peer_group="RR-CLIENTS"), ), ), ], ), state="rendered", ), ) self.assertEqual( sorted(self.execute_module(changed=False)["rendered"]), [ "set protocols bgp neighbor eth1 interface v6only peer-group RR-CLIENTS", "set protocols bgp neighbor eth1 interface v6only remote-as external", "set protocols bgp system-as 65536", ], ) def test_vyos_bgp_global_interface_v6only_replaced(self): set_module_args( dict( config=dict( as_number=65536, neighbor=[ dict(address="eth1", interface=dict(v6only=dict(remote_as=65002))), dict(address="RR-CLIENTS", peer_group=True, remote_as="external"), ], ), state="replaced", ), ) self.execute_module( changed=True, commands=[ "delete protocols bgp neighbor eth1 interface v6only peer-group RR-CLIENTS", "set protocols bgp neighbor eth1 interface v6only remote-as 65002", ], filename="vyos_bgp_global_v6only_config_14.cfg", ) + + def test_vyos_bgp_global_peer_group_named_like_option(self): + set_module_args( + dict( + config=dict( + as_number=65536, + neighbor=[dict(address="route_map", peer_group=True, remote_as=65536)], + ), + state="rendered", + ), + ) + self.assertEqual( + sorted(self.execute_module(changed=False)["rendered"]), + [ + "set protocols bgp peer-group route_map remote-as 65536", + "set protocols bgp system-as 65536", + ], + ) + + def test_vyos_bgp_global_peer_group_bare_parsed(self): + set_module_args( + dict( + running_config=load_fixture("vyos_bgp_global_peer_group_bare_config_14.cfg"), + state="parsed", + ), + ) + self.assertEqual( + self.execute_module(changed=False)["parsed"], + { + "as_number": 65001, + "neighbor": [ + {"address": "192.0.2.1", "peer_group_name": "RR-CLIENTS"}, + {"address": "AFONLY", "peer_group": True}, + {"address": "BARE", "peer_group": True}, + {"address": "RR-CLIENTS", "peer_group": True, "remote_as": 65001}, + ], + }, + ) + + def test_vyos_bgp_global_peer_group_bare_replaced(self): + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[ + dict(address="192.0.2.1", peer_group_name="RR-CLIENTS"), + dict(address="AFONLY", peer_group=True), + dict(address="RR-CLIENTS", peer_group=True, remote_as=65001), + ], + ), + state="replaced", + ), + ) + self.execute_module( + changed=True, + commands=["delete protocols bgp peer-group BARE"], + filename="vyos_bgp_global_peer_group_bare_config_14.cfg", + ) + + def test_vyos_bgp_global_peer_group_af_only_replaced(self): + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[ + dict(address="192.0.2.1", peer_group_name="RR-CLIENTS"), + dict(address="BARE", peer_group=True), + dict(address="RR-CLIENTS", peer_group=True, remote_as=65001), + ], + ), + state="replaced", + ), + ) + result = self.execute_module( + failed=True, + filename="vyos_bgp_global_peer_group_bare_config_14.cfg", + ) + self.assertIn( + "address-family settings of peer-group AFONLY with vyos_config", + result["msg"], + ) + + def test_vyos_bgp_global_peer_group_bare_rendered(self): + set_module_args( + dict( + config=dict(as_number=65001, neighbor=[dict(address="BARE", peer_group=True)]), + state="rendered", + ), + ) + self.assertEqual( + sorted(self.execute_module(changed=False)["rendered"]), + ["set protocols bgp peer-group BARE", "set protocols bgp system-as 65001"], + ) + + def test_vyos_bgp_global_peer_group_bare_merged(self): + set_module_args( + dict( + config=dict(as_number=65001, neighbor=[dict(address="NEW", peer_group=True)]), + state="merged", + ), + ) + self.execute_module( + changed=True, + commands=["set protocols bgp peer-group NEW"], + filename="vyos_bgp_global_peer_group_bare_config_14.cfg", + ) + + def test_vyos_bgp_global_peer_group_bare_merged_idempotent(self): + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[ + dict(address="192.0.2.1", peer_group_name="RR-CLIENTS"), + dict(address="AFONLY", peer_group=True), + dict(address="BARE", peer_group=True), + dict(address="RR-CLIENTS", peer_group=True, remote_as=65001), + ], + ), + state="merged", + ), + ) + self.execute_module( + changed=False, + filename="vyos_bgp_global_peer_group_bare_config_14.cfg", + ) + + def test_vyos_bgp_global_peer_group_same_name_rendered(self): + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[ + dict(address="eth1", interface=dict(v6only=dict(remote_as="external"))), + dict(address="eth1", peer_group=True, remote_as="external"), + ], + ), + state="rendered", + ), + ) + self.assertEqual( + sorted(self.execute_module(changed=False)["rendered"]), + [ + "set protocols bgp neighbor eth1 interface v6only remote-as external", + "set protocols bgp peer-group eth1 remote-as external", + "set protocols bgp system-as 65001", + ], + ) + + def test_vyos_bgp_global_peer_group_same_name_parsed(self): + set_module_args( + dict( + running_config=load_fixture("vyos_bgp_global_peer_group_same_name_config_14.cfg"), + state="parsed", + ), + ) + self.assertEqual( + self.execute_module(changed=False)["parsed"], + { + "as_number": 65001, + "neighbor": [ + {"address": "eth1", "interface": {"v6only": {"remote_as": "external"}}}, + {"address": "eth1", "peer_group": True, "remote_as": "external"}, + ], + }, + ) + + def test_vyos_bgp_global_peer_group_same_name_merged_idempotent(self): + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[ + dict(address="eth1", interface=dict(v6only=dict(remote_as="external"))), + dict(address="eth1", peer_group=True, remote_as="external"), + ], + ), + state="merged", + ), + ) + self.execute_module( + changed=False, + filename="vyos_bgp_global_peer_group_same_name_config_14.cfg", + ) + + def test_vyos_bgp_global_peer_group_same_name_replaced(self): + # the address-family settings of neighbor eth1 do not block deleting peer-group eth1 + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[ + dict(address="eth1", interface=dict(v6only=dict(remote_as="external"))), + ], + ), + state="replaced", + ), + ) + self.execute_module( + changed=True, + commands=["delete protocols bgp peer-group eth1"], + filename="vyos_bgp_global_peer_group_same_name_config_14.cfg", + ) + + def test_vyos_bgp_global_neighbor_same_name_replaced_af(self): + set_module_args( + dict( + config=dict( + as_number=65001, + neighbor=[dict(address="eth1", peer_group=True, remote_as="external")], + ), + state="replaced", + ), + ) + result = self.execute_module( + failed=True, + filename="vyos_bgp_global_peer_group_same_name_config_14.cfg", + ) + self.assertIn("address_family under neighbor eth1", result["msg"]) + + self.assertIn("address_family under neighbor eth1", result["msg"]) + + def test_vyos_bgp_global_remote_as_invalid(self): + for value in (0, 4294967295, True, [65001], 65001.5, "65001x"): + for neighbor in ( + dict(address="192.0.2.1", remote_as=value), + dict(address="eth1", interface=dict(v6only=dict(remote_as=value))), + ): + with self.subTest(value=value, neighbor=neighbor["address"]): + set_module_args( + dict( + config=dict(as_number=65536, neighbor=[neighbor]), + state="rendered", + ), + ) + result = self.execute_module(failed=True) + self.assertIn("remote_as must be an AS number", result["msg"]) diff --git a/tests/unit/modules/network/vyos/test_vyos_vrf.py b/tests/unit/modules/network/vyos/test_vyos_vrf.py index e86227a9..784f8d42 100644 --- a/tests/unit/modules/network/vyos/test_vyos_vrf.py +++ b/tests/unit/modules/network/vyos/test_vyos_vrf.py @@ -1,689 +1,768 @@ # (c) 2021 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . from __future__ import absolute_import, division, print_function __metaclass__ = type from unittest.mock import MagicMock, patch from ansible_collections.vyos.vyos.plugins.modules import vyos_vrf from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args from .vyos_module import TestVyosModule, load_fixture class TestVyosVrfModule(TestVyosModule): module = vyos_vrf def setUp(self): super(TestVyosVrfModule, self).setUp() self.fake_connection = MagicMock() self.fake_connection.get.return_value = "{}" self.fake_connection.get_device_info.return_value = { "version": "1.5", } self.fake_connection.get_device_info.return_value = { "network_os_major_version": "1.5", } patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos.get_connection", return_value=self.fake_connection, ).start() def _get_resource_connection_side_effect(module, *args, **kwargs): module._connection = self.fake_connection return self.fake_connection patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module_base.get_resource_connection", side_effect=_get_resource_connection_side_effect, ).start() patch( "ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts.get_resource_connection", side_effect=_get_resource_connection_side_effect, ).start() self.mock_execute_show_command = patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.vrf.vrf.VrfFacts.get_config", ).start() patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.vrf.vrf.get_os_version", return_value="1.5", ).start() patch( "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global.bgp_global.get_os_version", return_value="1.5", ).start() self.maxDiff = None def tearDown(self): super(TestVyosVrfModule, self).tearDown() patch.stopall() def load_fixtures(self, commands=None, filename=None): if filename is None: filename = "vyos_vrf_config.cfg" def load_from_file(*args, **kwargs): return load_fixture(filename) self.mock_execute_show_command.side_effect = load_from_file def test_vrf_merged_idempotent(self): set_module_args( dict( config=dict( bind_to_all=True, instances=[ dict( name="vrf-blue", description="blue-vrf", disable=False, table_id=100, vni=1000, ), dict( name="vrf-red", description="red-vrf", disable=True, table_id=101, vni=1001, address_family=[ dict( afi="ipv4", disable_forwarding=True, route_maps=[ dict(rm_name="rm1", protocol="rip"), ], ), dict( afi="ipv6", nht_no_resolve_via_default=True, ), ], protocols=dict( bgp=dict( as_number=65000, neighbor=[ dict( address="192.0.2.1", remote_as=65002, ), dict( address="1.1.1.3", remote_as=400, passive=True, ), ], ), ), ), ], ), state="merged", ), ) self.execute_module(changed=False, commands=[]) def test_vrf_merged(self): set_module_args( dict( config=dict( bind_to_all=False, instances=[ dict( name="vrf-green", description="green-vrf", table_id=110, vni=1010, protocols=dict( ospf=dict( log_adjacency_changes="detail", max_metric=dict( router_lsa=dict( administrative=True, on_shutdown=10, on_startup=10, ), ), default_information=dict( originate=dict( always=True, metric=10, metric_type=2, ), ), auto_cost=dict( reference_bandwidth=2, ), neighbor=[ dict( neighbor_id="192.0.11.12", poll_interval=10, priority=2, ), ], redistribute=[ dict( route_type="bgp", metric=10, metric_type=2, ), ], parameters=dict( router_id="192.0.1.1", rfc1583_compatibility=True, abr_type="cisco", ), areas=[ dict( area_id="2", area_type=dict( normal=True, ), authentication="plaintext-password", shortcut="enable", ), dict( area_id="3", area_type=dict( nssa=dict( set=True, ), ), ), dict( area_id="4", area_type=dict( stub=dict( default_cost=20, ), ), network=[ dict( address="192.0.2.0/24", ), ], range=[ dict( address="192.0.3.0/24", cost=10, ), dict( address="192.0.4.0/24", cost=12, ), ], ), ], ), ), ), ], ), state="merged", ), ) commands = [ "delete vrf bind-to-all", "set vrf name vrf-green table 110", "set vrf name vrf-green vni 1010", "set vrf name vrf-green description green-vrf", "set vrf name vrf-green protocols ospf log-adjacency-changes 'detail'", "set vrf name vrf-green protocols ospf max-metric router-lsa administrative", "set vrf name vrf-green protocols ospf max-metric router-lsa on-shutdown 10", "set vrf name vrf-green protocols ospf max-metric router-lsa on-startup 10", "set vrf name vrf-green protocols ospf default-information originate always", "set vrf name vrf-green protocols ospf default-information originate metric 10", "set vrf name vrf-green protocols ospf default-information originate metric-type 2", "set vrf name vrf-green protocols ospf auto-cost reference-bandwidth '2'", "set vrf name vrf-green protocols ospf neighbor 192.0.11.12", "set vrf name vrf-green protocols ospf neighbor 192.0.11.12 poll-interval 10", "set vrf name vrf-green protocols ospf neighbor 192.0.11.12 priority 2", "set vrf name vrf-green protocols ospf redistribute bgp", "set vrf name vrf-green protocols ospf redistribute bgp metric 10", "set vrf name vrf-green protocols ospf redistribute bgp metric-type 2", "set vrf name vrf-green protocols ospf parameters router-id '192.0.1.1'", "set vrf name vrf-green protocols ospf parameters rfc1583-compatibility", "set vrf name vrf-green protocols ospf parameters abr-type 'cisco'", "set vrf name vrf-green protocols ospf area '2'", "set vrf name vrf-green protocols ospf area 2 area-type normal", "set vrf name vrf-green protocols ospf area 2 authentication plaintext-password", "set vrf name vrf-green protocols ospf area 2 shortcut enable", "set vrf name vrf-green protocols ospf area '3'", "set vrf name vrf-green protocols ospf area 3 area-type nssa", "set vrf name vrf-green protocols ospf area '4'", "set vrf name vrf-green protocols ospf area 4 area-type stub default-cost 20", "set vrf name vrf-green protocols ospf area 4 network 192.0.2.0/24", "set vrf name vrf-green protocols ospf area 4 range 192.0.3.0/24", "set vrf name vrf-green protocols ospf area 4 range 192.0.3.0/24 cost 10", "set vrf name vrf-green protocols ospf area 4 range 192.0.4.0/24", "set vrf name vrf-green protocols ospf area 4 range 192.0.4.0/24 cost 12", ] self.execute_module(changed=True, commands=commands) def test_vrf_replaced(self): set_module_args( dict( config=dict( bind_to_all=True, instances=[ dict( name="vrf-blue", description="blue-vrf-replaced", disable=True, table_id=100, vni=1000, ), dict( name="vrf-red", description="red-vrf", disable=True, table_id=101, vni=1001, address_family=[ dict( afi="ipv4", disable_forwarding=False, route_maps=[ dict(rm_name="rm1", protocol="rip"), ], ), dict( afi="ipv6", nht_no_resolve_via_default=False, ), ], ), ], ), state="replaced", ), ) commands = [ "set vrf name vrf-blue description blue-vrf-replaced", "set vrf name vrf-blue disable", "delete vrf name vrf-red ip disable-forwarding", "delete vrf name vrf-red ipv6 nht no-resolve-via-default", ] self.execute_module(changed=True, commands=commands) def test_vrf_replaced_idempotent(self): set_module_args( dict( config=dict( bind_to_all=True, instances=[ dict( name="vrf-blue", description="blue-vrf", disable=False, table_id=100, vni=1000, ), dict( name="vrf-red", description="red-vrf", disable=True, table_id=101, vni=1001, address_family=[ dict( afi="ipv4", disable_forwarding=True, route_maps=[ dict(rm_name="rm1", protocol="rip"), ], ), dict( afi="ipv6", nht_no_resolve_via_default=True, ), ], ), ], ), state="replaced", ), ) self.execute_module(changed=False, commands=[]) def test_vrf_overridden(self): set_module_args( dict( config=dict( instances=[ dict( name="vrf-blue", description="blue-vrf", disable=True, table_id=103, vni=1002, ), dict( name="vrf-red", description="red-vrf", disable=True, table_id=101, vni=1001, protocols=dict( bgp=dict( as_number=65000, neighbor=[ dict( address="192.0.2.1", remote_as=65003, ), ], ), ), ), ], ), state="overridden", ), ) commands = [ "delete vrf name vrf-blue", "commit", "delete vrf name vrf-red", "commit", "set vrf name vrf-blue table 103", "set vrf name vrf-blue vni 1002", "set vrf name vrf-blue description blue-vrf", "set vrf name vrf-blue disable", "set vrf name vrf-red table 101", "set vrf name vrf-red vni 1001", "set vrf name vrf-red description red-vrf", "set vrf name vrf-red disable", "set vrf name vrf-red protocols bgp system-as 65000", "set vrf name vrf-red protocols bgp neighbor 192.0.2.1 remote-as 65003", "delete vrf bind-to-all", ] self.execute_module(changed=True, commands=commands) def test_vrf_overridden_idempotent(self): set_module_args( dict( config=dict( bind_to_all=True, instances=[ dict( name="vrf-blue", description="blue-vrf", disable=False, table_id=100, vni=1000, ), dict( name="vrf-red", description="red-vrf", disable=True, table_id=101, vni=1001, address_family=[ dict( afi="ipv4", disable_forwarding=True, nht_no_resolve_via_default=False, route_maps=[ dict(rm_name="rm1", protocol="rip"), ], ), dict( afi="ipv6", disable_forwarding=False, nht_no_resolve_via_default=True, ), ], protocols=dict( bgp=dict( as_number=65000, neighbor=[ dict( address="192.0.2.1", remote_as=65002, ), dict( address="1.1.1.3", remote_as=400, passive=True, ), ], ), ), ), ], ), state="overridden", ), ) self.execute_module(changed=False, commands=[]) def test_vrf_rendered(self): set_module_args( dict( config=dict( bind_to_all=True, instances=[ dict( name="vrf-green", description="green-vrf", disabled=True, table_id=105, vni=1000, ), dict( name="vrf-amber", description="amber-vrf", disable=False, table_id=111, vni=1001, address_family=[ dict( afi="ipv4", disable_forwarding=True, route_maps=[ dict(rm_name="rm1", protocol="ospf"), ], ), dict( afi="ipv6", nht_no_resolve_via_default=False, ), ], ), ], ), state="rendered", ), ) rendered_commands = [ "set vrf bind-to-all", "set vrf name vrf-green table 105", "set vrf name vrf-green vni 1000", "set vrf name vrf-green description green-vrf", "set vrf name vrf-green disable", "set vrf name vrf-amber table 111", "set vrf name vrf-amber vni 1001", "set vrf name vrf-amber description amber-vrf", "set vrf name vrf-amber ip protocol ospf route-map rm1", "set vrf name vrf-amber ip disable-forwarding", ] result = self.execute_module(changed=False) self.assertEqual( sorted(result["rendered"]), sorted(rendered_commands), result["rendered"], ) def test_vrf_parsed(self): commands = ( "set vrf bind-to-all", "set vrf name vrf1 description 'red'", "set vrf name vrf1 disable", "set vrf name vrf1 table 101", "set vrf name vrf1 vni 501", "set vrf name vrf2 description 'green'", "set vrf name vrf2 disable", "set vrf name vrf2 table 102", "set vrf name vrf2 vni 102", "set vrf name vrf1 ip disable-forwarding", "set vrf name vrf1 ip nht no-resolve-via-default", "set vrf name vrf-red ip protocol ospf route-map 'rm1'", "set vrf name vrf-red ipv6 nht no-resolve-via-default", ) parsed_str = "\n".join(commands) set_module_args(dict(running_config=parsed_str, state="parsed")) result = self.execute_module(changed=False) parsed_list = { "bind_to_all": True, "instances": [ { "address_family": [ { "afi": "ipv4", "disable_forwarding": True, "nht_no_resolve_via_default": True, }, ], "description": "red", "disable": True, "name": "vrf1", }, { "description": "green", "disable": True, "name": "vrf2", }, { "address_family": [ { "afi": "ipv4", "disable_forwarding": False, "nht_no_resolve_via_default": False, "route_maps": [ { "protocol": "ospf", "rm_name": "rm1", }, ], }, { "afi": "ipv6", "disable_forwarding": False, "nht_no_resolve_via_default": True, }, ], "disable": False, "name": "vrf-red", }, ], } self.assertEqual(parsed_list, result["parsed"]) def test_vrf_gathered(self): set_module_args(dict(state="gathered")) result = self.execute_module(changed=False) gathered_list = { "bind_to_all": True, "instances": [ { "description": "blue-vrf", "disable": False, "name": "vrf-blue", "table_id": 100, "vni": 1000, }, { "address_family": [ { "afi": "ipv4", "disable_forwarding": True, "nht_no_resolve_via_default": False, "route_maps": [ {"protocol": "rip", "rm_name": "rm1"}, ], }, { "afi": "ipv6", "disable_forwarding": False, "nht_no_resolve_via_default": True, }, ], "description": "red-vrf", "disable": True, "name": "vrf-red", "protocols": { "bgp": { "as_number": 65000, "neighbor": [ {"address": "1.1.1.3", "passive": True, "remote_as": 400}, {"address": "192.0.2.1", "remote_as": 65002}, ], }, }, "table_id": 101, "vni": 1001, }, ], } self.assertEqual(gathered_list, result["gathered"]) def test_vrf_deleted(self): set_module_args( dict( config=dict( bind_to_all=True, instances=[ dict( name="vrf-blue", ), ], ), state="deleted", ), ) commands = [ "delete vrf bind-to-all", "delete vrf name vrf-blue", ] self.execute_module(changed=True, commands=commands) def test_vrf_all_deleted(self): set_module_args( dict( state="deleted", ), ) commands = [ "delete vrf", ] self.execute_module(changed=True, commands=commands) + + def _bgp_global_patches(self, running_config=""): + """Device config seen by the address-family check of the VRF's BGP instance.""" + patch( + "ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.bgp_global." + "bgp_global.Bgp_global._get_config", + return_value=running_config, + ).start() + + def test_vrf_bgp_neighbor_removed(self): + self._bgp_global_patches() + set_module_args( + dict( + config=dict( + instances=[ + dict( + name="vrf-red", + protocols=dict( + bgp=dict( + as_number=65000, + neighbor=[dict(address="192.0.2.1", remote_as=65002)], + ), + ), + ), + ], + ), + state="replaced", + ), + ) + result = self.execute_module(changed=True) + self.assertIn("delete vrf name vrf-red protocols bgp neighbor 1.1.1.3", result["commands"]) + + def test_vrf_bgp_neighbor_removed_global_af(self): + # address-family settings of the global neighbor 1.1.1.3 do not block vrf-red's 1.1.1.3 + self._bgp_global_patches(load_fixture("vyos_vrf_bgp_af_config.cfg")) + set_module_args( + dict( + config=dict( + instances=[ + dict( + name="vrf-red", + protocols=dict( + bgp=dict( + as_number=65000, + neighbor=[dict(address="192.0.2.1", remote_as=65002)], + ), + ), + ), + ], + ), + state="replaced", + ), + ) + result = self.execute_module(changed=True) + self.assertIn("delete vrf name vrf-red protocols bgp neighbor 1.1.1.3", result["commands"]) + + def test_vrf_bgp_neighbor_removed_vrf_af(self): + # vrf-red's 192.0.2.1 has address-family settings + self._bgp_global_patches(load_fixture("vyos_vrf_bgp_af_config.cfg")) + set_module_args( + dict( + config=dict( + instances=[ + dict( + name="vrf-red", + protocols=dict( + bgp=dict( + as_number=65000, + neighbor=[dict(address="1.1.1.3", remote_as=400, passive=True)], + ), + ), + ), + ], + ), + state="replaced", + ), + ) + result = self.execute_module(failed=True) + self.assertIn("address_family under neighbor 192.0.2.1", result["msg"])