diff --git a/changelogs/fragments/t9658_static_routes_interface_next_hop.yaml b/changelogs/fragments/t9658_static_routes_interface_next_hop.yaml
new file mode 100644
index 00000000..e69de29b
diff --git a/plugins/module_utils/network/vyos/config/static_routes/static_routes.py b/plugins/module_utils/network/vyos/config/static_routes/static_routes.py
index 2a09c0f0..1c97e8c9 100644
--- a/plugins/module_utils/network/vyos/config/static_routes/static_routes.py
+++ b/plugins/module_utils/network/vyos/config/static_routes/static_routes.py
@@ -1,603 +1,616 @@
#
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The vyos_static_routes class
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 it's desired end-state is
created
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from copy import deepcopy
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import (
ConfigBase,
)
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
dict_diff,
remove_empties,
to_list,
)
from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import Facts
from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import (
dict_delete,
get_lst_diff_for_dicts,
get_lst_same_for_dicts,
get_route_type,
)
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 Static_routes(ConfigBase):
"""
The vyos_static_routes class
"""
gather_subset = ["!all", "!min"]
gather_network_resources = ["static_routes"]
def __init__(self, module):
super(Static_routes, self).__init__(module)
def get_static_routes_facts(self, data=None):
"""Get the 'facts' (the current configuration)
:rtype: A dictionary
:returns: The current configuration as a dictionary
"""
facts, _warnings = Facts(self._module).get_facts(
self.gather_subset,
self.gather_network_resources,
data=data,
)
static_routes_facts = facts["ansible_network_resources"].get("static_routes")
if not static_routes_facts:
return []
return static_routes_facts
def execute_module(self):
"""Execute the module
:rtype: A dictionary
:returns: The result from module execution
"""
result = {"changed": False}
warnings = list()
commands = list()
if self.state in self.ACTION_STATES:
existing_static_routes_facts = self.get_static_routes_facts()
else:
existing_static_routes_facts = []
if self.state in self.ACTION_STATES or self.state == "rendered":
commands.extend(self.set_config(existing_static_routes_facts))
if commands and self.state in self.ACTION_STATES:
if not self._module.check_mode:
self._connection.edit_config(commands)
result["changed"] = True
if self.state in self.ACTION_STATES:
result["commands"] = commands
if self.state in self.ACTION_STATES or self.state == "gathered":
changed_static_routes_facts = self.get_static_routes_facts()
elif self.state == "rendered":
result["rendered"] = commands
elif self.state == "parsed":
running_config = self._module.params["running_config"]
if not running_config:
self._module.fail_json(
msg="value of running_config parameter must not be empty for state parsed",
)
result["parsed"] = self.get_static_routes_facts(data=running_config)
else:
changed_static_routes_facts = []
if self.state in self.ACTION_STATES:
result["before"] = existing_static_routes_facts
if result["changed"]:
result["after"] = changed_static_routes_facts
elif self.state == "gathered":
result["gathered"] = changed_static_routes_facts
result["warnings"] = warnings
return result
def set_config(self, existing_static_routes_facts):
"""Collect the configuration from the args passed to the module,
collect the current configuration (as a dict from facts)
:rtype: A list
:returns: the commands necessary to migrate the current configuration
to the desired configuration
"""
want = self._module.params["config"]
have = existing_static_routes_facts
resp = self.set_state(want, have)
return to_list(resp)
def set_state(self, want, have):
"""Select the appropriate function based on the state provided
:param want: the desired configuration as a dictionary
:param have: the current configuration as a dictionary
:rtype: A list
:returns: the commands necessary to migrate the current configuration
to the desired configuration
"""
commands = []
if self.state in ("merged", "replaced", "overridden", "rendered") and not want:
self._module.fail_json(
msg="value of config parameter must not be empty for state {0}".format(self.state),
)
if self.state == "overridden":
commands.extend(self._state_overridden(want=want, have=have))
elif self.state == "deleted":
commands.extend(self._state_deleted(want=want, have=have))
elif want:
routes = self._get_routes(want)
for r in routes:
h_item = self.search_route_in_have(have, r["dest"])
if self.state in ("merged", "rendered"):
commands.extend(self._state_merged(want=r, have=h_item))
elif self.state == "replaced":
commands.extend(self._state_replaced(want=r, have=h_item))
return commands
def search_route_in_have(self, have, want_dest):
"""
This function returns the route if its found in
have config.
:param have:
:param dest:
:return: the matched route
"""
routes = self._get_routes(have)
for r in routes:
if r["dest"] == want_dest:
return r
return None
def _state_replaced(self, want, have):
"""The command generator when state is replaced
:rtype: A list
:returns: the commands necessary to migrate the current configuration
to the desired configuration
"""
commands = []
if have:
for key, value in want.items():
if value:
if key == "next_hops":
commands.extend(self._update_next_hop(want, have))
elif key == "blackhole_config":
commands.extend(self._update_blackhole(key, want, have))
commands.extend(self._state_merged(want, have))
return commands
def _state_overridden(self, want, have):
"""The command generator when state is overridden
:rtype: A list
:returns: the commands necessary to migrate the current configuration
to the desired configuration
"""
commands = []
routes = self._get_routes(have)
for r in routes:
route_in_want = self.search_route_in_have(want, r["dest"])
if not route_in_want:
commands.append(self._compute_command(r["dest"], remove=True))
routes = self._get_routes(want)
for r in routes:
route_in_have = self.search_route_in_have(have, r["dest"])
commands.extend(self._state_replaced(r, route_in_have))
return commands
def _state_merged(self, want, have, opr=True):
"""The command generator when state is merged
:rtype: A list
:returns: the commands necessary to merge the provided into
the current configuration
"""
commands = []
if have:
commands.extend(self._render_updates(want, have))
else:
commands.extend(self._render_set_commands(want))
return commands
def _state_deleted(self, want, have):
"""The command generator when state is deleted
:rtype: A list
:returns: the commands necessary to remove the current configuration
of the provided objects
"""
commands = []
if want:
routes = self._get_routes(want)
if not routes:
for w in want:
af = w["address_families"]
for item in af:
if self.afi_in_have(have, item):
commands.append(self._compute_command(afi=item["afi"], remove=True))
else:
routes = self._get_routes(have)
if self._is_ip_route_exist(routes):
commands.append(self._compute_command(afi="ipv4", remove=True))
if self._is_ip_route_exist(routes, "route6"):
commands.append(self._compute_command(afi="ipv6", remove=True))
return commands
def _render_set_commands(self, want):
"""
This function returns the list of commands to add attributes which are
present in want
:param want:
:return: list of commands.
"""
commands = []
have = {}
for key, value in want.items():
if value:
if key == "dest":
commands.append(self._compute_command(dest=want["dest"]))
elif key == "blackhole_config":
commands.extend(self._add_blackhole(key, want, have))
elif key == "next_hops":
commands.extend(self._add_next_hop(want, have))
return commands
def _add_blackhole(self, key, want, have):
"""
This function gets the diff for blackhole config specific attributes
and form the commands for attributes which are present in want but not in have.
:param key:
:param want:
:param have:
:return: list of commands
"""
commands = []
want_copy = deepcopy(remove_empties(want))
have_copy = deepcopy(remove_empties(have))
want_blackhole = want_copy.get(key) or {}
have_blackhole = have_copy.get(key) or {}
updates = dict_delete(want_blackhole, have_blackhole)
if updates:
for attrib, value in updates.items():
if value:
if attrib == "distance":
commands.append(
self._compute_command(
dest=want["dest"],
key="blackhole",
attrib=attrib,
remove=False,
value=str(value),
),
)
elif attrib == "type":
commands.append(self._compute_command(dest=want["dest"], key="blackhole"))
return commands
def _add_next_hop(self, want, have, opr=True):
"""
This function gets the diff for next hop specific attributes
and form the commands to add attributes which are present in want but not in have.
:param want:
:param have:
:return: list of commands.
"""
commands = []
want_copy = deepcopy(remove_empties(want))
have_copy = deepcopy(remove_empties(have))
if not opr:
diff_next_hops = get_lst_same_for_dicts(want_copy, have_copy, "next_hops")
else:
diff_next_hops = get_lst_diff_for_dicts(want_copy, have_copy, "next_hops")
if diff_next_hops:
for hop in diff_next_hops:
for element in hop:
if element == "forward_router_address":
commands.append(
self._compute_command(
dest=want["dest"],
key="next-hop",
value=hop[element],
opr=opr,
),
)
elif element == "enabled" and not hop[element]:
commands.append(
- self._compute_command(
- dest=want["dest"],
- key="next-hop",
- attrib=hop["forward_router_address"],
- value="disable",
- opr=opr,
- ),
+ self._hop_attrib_command(want["dest"], hop, "", "disable", opr=opr),
)
elif element == "admin_distance":
commands.append(
- self._compute_command(
- dest=want["dest"],
- key="next-hop",
- attrib=hop["forward_router_address"] + " " + "distance",
- value=str(hop[element]),
+ self._hop_attrib_command(
+ want["dest"],
+ hop,
+ " distance",
+ str(hop[element]),
opr=opr,
),
)
elif element == "interface" and LooseVersion(
get_os_version(self._module),
) < LooseVersion("1.4"):
commands.append(
self._compute_command(
dest=want["dest"],
key="next-hop-interface",
value=hop[element],
opr=opr,
).replace("route", "interface-route"),
)
elif element == "interface" and LooseVersion(
get_os_version(self._module),
) >= LooseVersion("1.4"):
commands.append(
self._compute_command(
dest=want["dest"],
key="interface",
value=hop[element],
opr=opr,
),
)
return commands
def _update_blackhole(self, key, want, have):
"""
This function gets the difference for blackhole dict and
form the commands to delete the attributes which are present in have but not in want.
:param want:
:param have:
:return: list of commands
:param key:
:param want:
:param have:
:return: list of commands
"""
commands = []
want_copy = deepcopy(remove_empties(want))
have_copy = deepcopy(remove_empties(have))
want_blackhole = want_copy.get(key) or {}
have_blackhole = have_copy.get(key) or {}
updates = dict_delete(have_blackhole, want_blackhole)
if updates:
for attrib, value in updates.items():
if value:
if attrib == "distance":
commands.append(
self._compute_command(
dest=want["dest"],
key="blackhole",
attrib=attrib,
remove=True,
value=str(value),
),
)
elif attrib == "type" and "distance" not in want_blackhole.keys():
commands.append(
self._compute_command(dest=want["dest"], key="blackhole", remove=True),
)
return commands
def _update_next_hop(self, want, have, opr=True):
"""
This function gets the difference for next_hops list and
form the commands to delete the attributes which are present in have but not in want.
:param want:
:param have:
:return: list of commands
"""
commands = []
want_copy = deepcopy(remove_empties(want))
have_copy = deepcopy(remove_empties(have))
diff_next_hops = get_lst_diff_for_dicts(have_copy, want_copy, "next_hops")
if diff_next_hops:
for hop in diff_next_hops:
for element in hop:
if element == "forward_router_address":
commands.append(
self._compute_command(
dest=want["dest"],
key="next-hop",
value=hop[element],
remove=True,
),
)
elif element == "enabled":
commands.append(
- self._compute_command(
- dest=want["dest"],
- key="next-hop",
- attrib=hop["forward_router_address"],
- value="disable",
- remove=True,
- ),
+ self._hop_attrib_command(want["dest"], hop, "", "disable", remove=True),
)
elif element == "admin_distance":
commands.append(
- self._compute_command(
- dest=want["dest"],
- key="next-hop",
- attrib=hop["forward_router_address"] + " " + "distance",
- value=str(hop[element]),
+ self._hop_attrib_command(
+ want["dest"],
+ hop,
+ " distance",
+ str(hop[element]),
remove=True,
),
)
elif element == "interface" and LooseVersion(
get_os_version(self._module),
) < LooseVersion("1.4"):
commands.append(
self._compute_command(
dest=want["dest"],
key="next-hop-interface",
value=hop[element],
remove=True,
).replace("route", "interface-route"),
)
elif element == "interface" and LooseVersion(
get_os_version(self._module),
) >= LooseVersion("1.4"):
commands.append(
self._compute_command(
dest=want["dest"],
key="interface",
value=hop[element],
remove=True,
),
)
return commands
def _render_updates(self, want, have, opr=True):
"""
This function takes the diff between want and have and
invokes the appropriate functions to create the commands
to update the attributes.
:param want:
:param have:
:return: list of commands
"""
commands = []
want_nh = want.get("next_hops") or []
# delete static route operation per destination
if not opr and not want_nh:
commands.append(self._compute_command(dest=want["dest"], remove=True))
else:
temp_have_next_hops = have.pop("next_hops", None)
temp_want_next_hops = want.pop("next_hops", None)
updates = dict_diff(have, want)
if temp_have_next_hops:
have["next_hops"] = temp_have_next_hops
if temp_want_next_hops:
want["next_hops"] = temp_want_next_hops
commands.extend(self._add_next_hop(want, have, opr=opr))
if opr and updates:
for key, value in updates.items():
if value:
if key == "blackhole_config":
commands.extend(self._add_blackhole(key, want, have))
return commands
+ def _hop_attrib_command(self, dest, hop, attrib, value, **kwargs):
+ """
+ Build the command for an attribute (distance/disable) of a next hop, addressing
+ the hop by its gateway address or, for interface-only hops, by its interface.
+ """
+ if hop.get("forward_router_address"):
+ return self._compute_command(
+ dest=dest,
+ key="next-hop",
+ attrib=hop["forward_router_address"] + attrib,
+ value=value,
+ **kwargs
+ )
+ if LooseVersion(get_os_version(self._module)) < LooseVersion("1.4"):
+ return self._compute_command(
+ dest=dest,
+ key="next-hop-interface",
+ attrib=hop["interface"] + attrib,
+ value=value,
+ **kwargs
+ ).replace("route", "interface-route")
+ return self._compute_command(
+ dest=dest, key="interface", attrib=hop["interface"] + attrib, value=value, **kwargs
+ )
+
def _compute_command(
self,
dest=None,
key=None,
attrib=None,
value=None,
remove=False,
afi=None,
opr=True,
):
"""
This functions construct the required command based on the passed arguments.
:param dest:
:param key:
:param attrib:
:param value:
:param remove:
:return: constructed command
"""
if remove or not opr:
cmd = "delete protocols static " + self.get_route_type(dest, afi)
else:
cmd = "set protocols static " + self.get_route_type(dest, afi)
if dest:
cmd += " " + dest
if key:
cmd += " " + key
if attrib:
cmd += " " + attrib
if value:
cmd += " '" + value + "'"
return cmd
def afi_in_have(self, have, w_item):
"""
This functions checks for the afi
list in have
:param have:
:param w_item:
:return:
"""
if have:
for h in have:
af = h.get("address_families") or []
for item in af:
if w_item["afi"] == item["afi"]:
return True
return False
def get_route_type(self, dest=None, afi=None):
"""
This function returns the route type based on
destination ip address or afi
:param address:
:return:
"""
if dest:
return get_route_type(dest)
elif afi == "ipv4":
return "route"
elif afi == "ipv6":
return "route6"
def _is_ip_route_exist(self, routes, type="route"):
"""
This functions checks for the type of route.
:param routes:
:param type:
:return: True/False
"""
for r in routes:
if type == self.get_route_type(r["dest"]):
return True
return False
def _get_routes(self, lst):
"""
This function returns the list of routes
:param lst: list of address families
:return: list of routes
"""
r_list = []
for item in lst:
af = item["address_families"]
for element in af:
routes = element.get("routes") or []
for r in routes:
r_list.append(r)
return r_list
diff --git a/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py b/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py
index 1bce772c..c3a5e793 100644
--- a/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py
+++ b/plugins/module_utils/network/vyos/facts/static_routes/static_routes.py
@@ -1,177 +1,166 @@
#
# -*- coding: utf-8 -*-
# Copyright 2019 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The vyos static_routes 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.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from copy import deepcopy
from re import M, findall, search
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import utils
from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.static_routes.static_routes import (
Static_routesArgs,
)
from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import (
get_route_type,
)
class Static_routesFacts(object):
"""The vyos static_routes fact class"""
def __init__(self, module, subspec="config", options="options"):
self._module = module
self.argument_spec = Static_routesArgs.argument_spec
spec = deepcopy(self.argument_spec)
if subspec:
if options:
facts_argument_spec = spec[subspec][options]
else:
facts_argument_spec = spec[subspec]
else:
facts_argument_spec = spec
self.generated_spec = utils.generate_dict(facts_argument_spec)
def get_device_data(self, connection):
return connection.get_config()
def populate_facts(self, connection, ansible_facts, data=None):
"""Populate the facts for static_routes
:param connection: the device connection
:param ansible_facts: Facts dictionary
:param data: previously collected conf
:rtype: dictionary
:returns: facts
"""
if not data:
data = self.get_device_data(connection)
# typically data is populated from the current device configuration
# data = connection.get('show running-config | section ^interface')
# using mock data instead
objs = []
r_v4 = []
r_v6 = []
af = []
static_routes = findall(r"set protocols static route(6)? (\S+)", data, M)
if static_routes:
for route in set(static_routes):
route_regex = r" %s .+$" % route[1]
cfg = findall(route_regex, data, M)
sr = self.render_config(cfg)
sr["dest"] = route[1].strip("'")
afi = self.get_afi(sr["dest"])
if afi == "ipv4":
r_v4.append(sr)
else:
r_v6.append(sr)
if r_v4:
afi_v4 = {"afi": "ipv4", "routes": r_v4}
af.append(afi_v4)
if r_v6:
afi_v6 = {"afi": "ipv6", "routes": r_v6}
af.append(afi_v6)
config = {"address_families": af}
if config:
objs.append(config)
ansible_facts["ansible_network_resources"].pop("static_routes", None)
facts = {}
if objs:
facts["static_routes"] = []
params = utils.validate_config(self.argument_spec, {"config": objs})
for cfg in params["config"]:
facts["static_routes"].append(utils.remove_empties(cfg))
ansible_facts["ansible_network_resources"].update(facts)
return ansible_facts
def render_config(self, conf):
"""
Render config as dictionary structure and delete keys
from spec for null values
:param spec: The facts tree, generated from the argspec
:param conf: The configuration
:rtype: dictionary
:returns: The generated config
"""
next_hops_conf = "\n".join(filter(lambda x: ("next-hop" in x or "interface" in x), conf))
blackhole_conf = "\n".join(filter(lambda x: ("blackhole" in x), conf))
routes_dict = {
"blackhole_config": self.parse_blackhole(blackhole_conf),
"next_hops": self.parse_next_hop(next_hops_conf),
}
return routes_dict
def parse_blackhole(self, conf):
blackhole = None
if conf:
distance = search(r"^.*blackhole distance (.\S+)", conf, M)
bh = conf.find("blackhole")
if distance is not None:
blackhole = {}
value = distance.group(1).strip("'")
blackhole["distance"] = int(value)
elif bh:
blackhole = {}
blackhole["type"] = "blackhole"
return blackhole
def get_afi(self, address):
route_type = get_route_type(address)
if route_type == "route":
return "ipv4"
elif route_type == "route6":
return "ipv6"
def parse_next_hop(self, conf):
nh_list = None
- nh_info = {}
if conf:
- nh_list = []
- hop_list = [
- match[0] if match[0] else match[1]
- for match in findall(r"^.*next-hop(.+)|(\s+interface.+)$", conf, M)
- ]
- if hop_list:
- for hop in hop_list:
- distance = search(r"^.*distance (.\S+)", hop, M)
- interface = search(r"^.*interface (.\S+)", hop, M)
-
- dis = hop.find("disable")
- hop_info = hop.split(" ")
-
+ # Each hop is keyed on what identifies it on the device: the gateway address
+ # for "next-hop X ..." lines, the interface name for "interface X ..." lines
+ # (or "next-hop-interface X ..." for VyOS 1.3 interface-route).
+ hops = {}
+ for line in conf.splitlines():
+ match = search(
+ r"\s(next-hop-interface|next-hop|interface) '?([^'\s]+)'?(.*)$", line
+ )
+ if not match:
+ continue
+ kind, name, rest = match.groups()
+ if kind == "next-hop":
+ hop = hops.setdefault((kind, name), {"forward_router_address": name})
+ interface = search(r"\binterface '?([^'\s]+)", rest)
if interface:
- nh_info["interface"] = interface.group(1).strip("'")
- else:
- nh_info = {"forward_router_address": hop_info[1].strip("'")}
- if distance:
- value = distance.group(1).strip("'")
- nh_info["admin_distance"] = int(value)
- elif dis >= 1:
- nh_info["enabled"] = False
- for element in nh_list:
- if element.get("forward_router_address") == nh_info.get(
- "forward_router_address",
- ):
- if "admin_distance" in nh_info.keys():
- element["admin_distance"] = nh_info["admin_distance"]
- if "enabled" in nh_info.keys():
- element["enabled"] = nh_info["enabled"]
- nh_info = None
- if nh_info is not None:
- nh_list.append(nh_info)
- nh_info = {}
+ hop["interface"] = interface.group(1)
+ else:
+ hop = hops.setdefault(("interface", name), {"interface": name})
+ distance = search(r"\bdistance '?(\d+)", rest)
+ if distance:
+ hop["admin_distance"] = int(distance.group(1))
+ if search(r"\bdisable\b", rest):
+ hop["enabled"] = False
+ nh_list = list(hops.values())
return nh_list
diff --git a/tests/unit/modules/network/vyos/fixtures/vyos_static_routes_interface_config.cfg b/tests/unit/modules/network/vyos/fixtures/vyos_static_routes_interface_config.cfg
new file mode 100644
index 00000000..7750ea06
--- /dev/null
+++ b/tests/unit/modules/network/vyos/fixtures/vyos_static_routes_interface_config.cfg
@@ -0,0 +1,4 @@
+set protocols static route 10.0.0.0/8 interface 'eth0'
+set protocols static route 10.0.0.0/8 interface eth1 distance '20'
+set protocols static route 10.0.0.0/8 interface eth2 disable
+set protocols static route 10.0.0.0/8 next-hop 192.0.2.1 distance '10'
diff --git a/tests/unit/modules/network/vyos/test_vyos_static_routes.py b/tests/unit/modules/network/vyos/test_vyos_static_routes.py
index 955c997a..73c0d2c3 100644
--- a/tests/unit/modules/network/vyos/test_vyos_static_routes.py
+++ b/tests/unit/modules/network/vyos/test_vyos_static_routes.py
@@ -1,278 +1,311 @@
# (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_static_routes
from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args
from .vyos_module import TestVyosModule, load_fixture
class TestVyosStaticRoutesModule(TestVyosModule):
module = vyos_static_routes
def setUp(self):
super(TestVyosStaticRoutesModule, self).setUp()
self.mock_get_config = patch(
"ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network.Config.get_config",
)
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch(
"ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network.Config.load_config",
)
self.load_config = self.mock_load_config.start()
self.mock_get_resource_connection_config = patch(
"ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection",
)
self.get_resource_connection_config = self.mock_get_resource_connection_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.static_routes.static_routes.Static_routesFacts.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.static_routes.static_routes.get_os_version",
)
self.test_version = "1.3"
self.get_os_version = self.mock_get_os_version.start()
self.get_os_version.return_value = self.test_version
def tearDown(self):
super(TestVyosStaticRoutesModule, self).tearDown()
self.mock_get_resource_connection_config.stop()
self.mock_get_resource_connection_facts.stop()
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_execute_show_command.stop()
def load_fixtures(self, commands=None, filename=None):
def load_from_file(*args, **kwargs):
return load_fixture("vyos_static_routes_config.cfg")
self.execute_show_command.side_effect = load_from_file
def test_vyos_static_routes_merged(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.48/28",
next_hops=[
dict(
forward_router_address="192.0.2.9",
admin_distance=10,
),
dict(
forward_router_address="192.0.2.10",
interface="eth0",
),
],
),
],
),
],
),
],
state="merged",
),
)
commands = [
"set protocols static route 192.0.2.48/28",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'",
"set protocols static route 192.0.2.48/28 next-hop 192.0.2.9 distance '10'",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'",
"set protocols static interface-route 192.0.2.48/28 next-hop-interface 'eth0'",
]
self.execute_module(changed=True, commands=commands)
def test_vyos_static_routes_merged_idempotent(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.32/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="merged",
),
)
self.execute_module(changed=False, commands=[])
def test_vyos_static_routes_replaced(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.48/28",
next_hops=[
dict(
forward_router_address="192.0.2.9",
interface="eth0",
),
dict(
forward_router_address="192.0.2.10",
admin_distance=10,
),
],
),
],
),
],
),
],
state="replaced",
),
)
commands = [
"set protocols static route 192.0.2.48/28",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'",
"set protocols static interface-route 192.0.2.48/28 next-hop-interface 'eth0'",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'",
"set protocols static route 192.0.2.48/28 next-hop 192.0.2.10 distance '10'",
]
self.execute_module(changed=True, commands=commands)
def test_vyos_static_routes_replaced_idempotent(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.32/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="replaced",
),
)
self.execute_module(changed=False, commands=[])
def test_vyos_static_routes_overridden(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.48/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="overridden",
),
)
commands = [
"delete protocols static route 192.0.2.32/28",
"set protocols static route 192.0.2.48/28",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'",
]
self.execute_module(changed=True, commands=commands)
def test_vyos_static_routes_overridden_idempotent(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.32/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="overridden",
),
)
self.execute_module(changed=False, commands=[])
def test_vyos_static_routes_deleted(self):
set_module_args(
dict(
config=[dict(address_families=[dict(afi="ipv4")])],
state="deleted",
),
)
commands = ["delete protocols static route"]
self.execute_module(changed=True, commands=commands)
+
+ def test_vyos_static_routes_merged_interface_next_hops(self):
+ set_module_args(
+ dict(
+ config=[
+ dict(
+ address_families=[
+ dict(
+ afi="ipv4",
+ routes=[
+ dict(
+ dest="10.0.0.0/8",
+ next_hops=[
+ dict(interface="eth3", admin_distance=30),
+ dict(interface="eth4", enabled=False),
+ ],
+ ),
+ ],
+ ),
+ ],
+ ),
+ ],
+ state="merged",
+ ),
+ )
+ commands = [
+ "set protocols static route 10.0.0.0/8",
+ "set protocols static interface-route 10.0.0.0/8 next-hop-interface 'eth3'",
+ "set protocols static interface-route 10.0.0.0/8 next-hop-interface eth3 distance '30'",
+ "set protocols static interface-route 10.0.0.0/8 next-hop-interface 'eth4'",
+ "set protocols static interface-route 10.0.0.0/8 next-hop-interface eth4 'disable'",
+ ]
+ self.execute_module(changed=True, commands=commands)
diff --git a/tests/unit/modules/network/vyos/test_vyos_static_routes14.py b/tests/unit/modules/network/vyos/test_vyos_static_routes14.py
index 2dd4c0aa..53be6f81 100644
--- a/tests/unit/modules/network/vyos/test_vyos_static_routes14.py
+++ b/tests/unit/modules/network/vyos/test_vyos_static_routes14.py
@@ -1,278 +1,366 @@
# (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_static_routes
from ansible_collections.vyos.vyos.tests.unit.modules.utils import set_module_args
from .vyos_module import TestVyosModule, load_fixture
class TestVyosStaticRoutesModule14(TestVyosModule):
module = vyos_static_routes
def setUp(self):
super(TestVyosStaticRoutesModule14, self).setUp()
self.mock_get_config = patch(
"ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network.Config.get_config",
)
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch(
"ansible_collections.ansible.netcommon.plugins.module_utils.network.common.network.Config.load_config",
)
self.load_config = self.mock_load_config.start()
self.mock_get_resource_connection_config = patch(
"ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base.get_resource_connection",
)
self.get_resource_connection_config = self.mock_get_resource_connection_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.static_routes.static_routes.Static_routesFacts.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.static_routes.static_routes.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
def tearDown(self):
super(TestVyosStaticRoutesModule14, self).tearDown()
self.mock_get_resource_connection_config.stop()
self.mock_get_resource_connection_facts.stop()
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_execute_show_command.stop()
def load_fixtures(self, commands=None, filename=None):
def load_from_file(*args, **kwargs):
- return load_fixture("vyos_static_routes_config.cfg")
+ return load_fixture(filename or "vyos_static_routes_config.cfg")
self.execute_show_command.side_effect = load_from_file
def test_vyos_static_routes_merged(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.48/28",
next_hops=[
dict(
forward_router_address="192.0.2.9",
admin_distance=10,
),
dict(
forward_router_address="192.0.2.10",
interface="eth0",
),
],
),
],
),
],
),
],
state="merged",
),
)
commands = [
"set protocols static route 192.0.2.48/28",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'",
"set protocols static route 192.0.2.48/28 next-hop 192.0.2.9 distance '10'",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'",
"set protocols static route 192.0.2.48/28 interface 'eth0'",
]
self.execute_module(changed=True, commands=commands)
def test_vyos_static_routes_merged_idempotent(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.32/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="merged",
),
)
self.execute_module(changed=False, commands=[])
def test_vyos_static_routes_replaced(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.48/28",
next_hops=[
dict(
forward_router_address="192.0.2.9",
interface="eth0",
),
dict(
forward_router_address="192.0.2.10",
admin_distance=10,
),
],
),
],
),
],
),
],
state="replaced",
),
)
commands = [
"set protocols static route 192.0.2.48/28",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'",
"set protocols static route 192.0.2.48/28 interface 'eth0'",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'",
"set protocols static route 192.0.2.48/28 next-hop 192.0.2.10 distance '10'",
]
self.execute_module(changed=True, commands=commands)
def test_vyos_static_routes_replaced_idempotent(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.32/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="replaced",
),
)
self.execute_module(changed=False, commands=[])
def test_vyos_static_routes_overridden(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.48/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="overridden",
),
)
commands = [
"delete protocols static route 192.0.2.32/28",
"set protocols static route 192.0.2.48/28",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.9'",
"set protocols static route 192.0.2.48/28 next-hop '192.0.2.10'",
]
self.execute_module(changed=True, commands=commands)
def test_vyos_static_routes_overridden_idempotent(self):
set_module_args(
dict(
config=[
dict(
address_families=[
dict(
afi="ipv4",
routes=[
dict(
dest="192.0.2.32/28",
next_hops=[
dict(forward_router_address="192.0.2.9"),
dict(forward_router_address="192.0.2.10"),
],
),
],
),
],
),
],
state="overridden",
),
)
self.execute_module(changed=False, commands=[])
def test_vyos_static_routes_deleted(self):
set_module_args(
dict(
config=[dict(address_families=[dict(afi="ipv4")])],
state="deleted",
),
)
commands = ["delete protocols static route"]
self.execute_module(changed=True, commands=commands)
+
+ def _interface_route(self, next_hops):
+ return [
+ dict(
+ address_families=[
+ dict(afi="ipv4", routes=[dict(dest="10.0.0.0/8", next_hops=next_hops)]),
+ ],
+ ),
+ ]
+
+ def _interface_hops(self):
+ return [
+ dict(interface="eth0"),
+ dict(interface="eth1", admin_distance=20),
+ dict(interface="eth2", enabled=False),
+ dict(forward_router_address="192.0.2.1", admin_distance=10),
+ ]
+
+ def test_vyos_static_routes_parsed_interface_next_hops(self):
+ set_module_args(
+ dict(
+ running_config=load_fixture("vyos_static_routes_interface_config.cfg"),
+ state="parsed",
+ ),
+ )
+ result = self.execute_module(changed=False)
+ self.assertEqual(result["parsed"], self._interface_route(self._interface_hops()))
+
+ def test_vyos_static_routes_merged_interface_next_hops_idempotent(self):
+ set_module_args(dict(config=self._interface_route(self._interface_hops()), state="merged"))
+ self.execute_module(
+ changed=False,
+ commands=[],
+ filename="vyos_static_routes_interface_config.cfg",
+ )
+
+ def test_vyos_static_routes_merged_interface_next_hops(self):
+ set_module_args(
+ dict(
+ config=self._interface_route(
+ [
+ dict(interface="eth3", admin_distance=30),
+ dict(interface="eth4", enabled=False),
+ ],
+ ),
+ state="merged",
+ ),
+ )
+ commands = [
+ "set protocols static route 10.0.0.0/8 interface 'eth3'",
+ "set protocols static route 10.0.0.0/8 interface eth3 distance '30'",
+ "set protocols static route 10.0.0.0/8 interface 'eth4'",
+ "set protocols static route 10.0.0.0/8 interface eth4 'disable'",
+ ]
+ self.execute_module(
+ changed=True,
+ commands=commands,
+ filename="vyos_static_routes_interface_config.cfg",
+ )
+
+ def test_vyos_static_routes_replaced_interface_next_hops(self):
+ set_module_args(
+ dict(
+ config=self._interface_route(
+ [dict(interface="eth0"), dict(interface="eth1", admin_distance=20)],
+ ),
+ state="replaced",
+ ),
+ )
+ commands = [
+ "delete protocols static route 10.0.0.0/8 interface 'eth2'",
+ "delete protocols static route 10.0.0.0/8 interface eth2 'disable'",
+ "delete protocols static route 10.0.0.0/8 next-hop '192.0.2.1'",
+ "delete protocols static route 10.0.0.0/8 next-hop 192.0.2.1 distance '10'",
+ ]
+ self.execute_module(
+ changed=True,
+ commands=commands,
+ filename="vyos_static_routes_interface_config.cfg",
+ )
+
+ def test_vyos_static_routes_deleted_interface_next_hops(self):
+ set_module_args(dict(config=[dict(address_families=[dict(afi="ipv4")])], state="deleted"))
+ self.execute_module(
+ changed=True,
+ commands=["delete protocols static route"],
+ filename="vyos_static_routes_interface_config.cfg",
+ )