diff --git a/plugins/action/__init__.py b/plugins/action/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/action/vyos.py b/plugins/action/vyos.py new file mode 100644 index 0000000..cab2f3f --- /dev/null +++ b/plugins/action/vyos.py @@ -0,0 +1,129 @@ +# +# (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 . +# +from __future__ import absolute_import, division, print_function + +__metaclass__ = type + +import sys +import copy + +from ansible_collections.ansible.netcommon.plugins.action.network import ( + ActionModule as ActionNetworkModule, +) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + load_provider, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + vyos_provider_spec, +) +from ansible.utils.display import Display + +display = Display() + + +class ActionModule(ActionNetworkModule): + def run(self, tmp=None, task_vars=None): + del tmp # tmp no longer has any effect + + module_name = self._task.action.split(".")[-1] + self._config_module = True if module_name == "vyos_config" else False + persistent_connection = self._play_context.connection.split(".")[-1] + warnings = [] + + if persistent_connection == "network_cli": + provider = self._task.args.get("provider", {}) + if any(provider.values()): + display.warning( + "provider is unnecessary when using network_cli and will be ignored" + ) + del self._task.args["provider"] + elif self._play_context.connection == "local": + provider = load_provider(vyos_provider_spec, self._task.args) + pc = copy.deepcopy(self._play_context) + pc.connection = "ansible.netcommon.network_cli" + pc.network_os = "vyos.vyos.vyos" + pc.remote_addr = provider["host"] or self._play_context.remote_addr + pc.port = int(provider["port"] or self._play_context.port or 22) + pc.remote_user = ( + provider["username"] or self._play_context.connection_user + ) + pc.password = provider["password"] or self._play_context.password + pc.private_key_file = ( + provider["ssh_keyfile"] or self._play_context.private_key_file + ) + + connection = self._shared_loader_obj.connection_loader.get( + "ansible.netcommon.persistent", + pc, + sys.stdin, + task_uuid=self._task._uuid, + ) + + # TODO: Remove below code after ansible minimal is cut out + if connection is None: + pc.connection = "network_cli" + pc.network_os = "vyos" + connection = self._shared_loader_obj.connection_loader.get( + "persistent", pc, sys.stdin, task_uuid=self._task._uuid + ) + + display.vvv( + "using connection plugin %s (was local)" % pc.connection, + pc.remote_addr, + ) + + command_timeout = ( + int(provider["timeout"]) + if provider["timeout"] + else connection.get_option("persistent_command_timeout") + ) + connection.set_options( + direct={"persistent_command_timeout": command_timeout} + ) + + socket_path = connection.run() + display.vvvv("socket_path: %s" % socket_path, pc.remote_addr) + if not socket_path: + return { + "failed": True, + "msg": "unable to open shell. Please see: " + + "https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell", + } + + task_vars["ansible_socket"] = socket_path + warnings.append( + [ + "connection local support for this module is deprecated and will be removed in version 2.14, use connection %s" + % pc.connection + ] + ) + else: + return { + "failed": True, + "msg": "Connection type %s is not valid for this module" + % self._play_context.connection, + } + + result = super(ActionModule, self).run(task_vars=task_vars) + if warnings: + if "warnings" in result: + result["warnings"].extend(warnings) + else: + result["warnings"] = warnings + return result diff --git a/plugins/cliconf/__init__.py b/plugins/cliconf/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/cliconf/vyos.py b/plugins/cliconf/vyos.py new file mode 100644 index 0000000..3033603 --- /dev/null +++ b/plugins/cliconf/vyos.py @@ -0,0 +1,342 @@ +# +# (c) 2017 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 + +DOCUMENTATION = """ +--- +author: Ansible Networking Team +cliconf: vyos +short_description: Use vyos cliconf to run command on VyOS platform +description: + - This vyos plugin provides low level abstraction apis for + sending and receiving CLI commands from VyOS network devices. +version_added: "2.4" +""" + +import re +import json + +from ansible.errors import AnsibleConnectionFailure +from ansible.module_utils._text import to_text +from ansible.module_utils.common._collections_compat import Mapping +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import ( + NetworkConfig, +) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, +) +from ansible.plugins.cliconf import CliconfBase + + +class Cliconf(CliconfBase): + def get_device_info(self): + device_info = {} + + device_info["network_os"] = "vyos" + reply = self.get("show version") + data = to_text(reply, errors="surrogate_or_strict").strip() + + match = re.search(r"Version:\s*(.*)", data) + if match: + device_info["network_os_version"] = match.group(1) + + match = re.search(r"HW model:\s*(\S+)", data) + if match: + device_info["network_os_model"] = match.group(1) + + reply = self.get("show host name") + device_info["network_os_hostname"] = to_text( + reply, errors="surrogate_or_strict" + ).strip() + + return device_info + + def get_config(self, flags=None, format=None): + if format: + option_values = self.get_option_values() + if format not in option_values["format"]: + raise ValueError( + "'format' value %s is invalid. Valid values of format are %s" + % (format, ", ".join(option_values["format"])) + ) + + if not flags: + flags = [] + + if format == "text": + command = "show configuration" + else: + command = "show configuration commands" + + command += " ".join(to_list(flags)) + command = command.strip() + + out = self.send_command(command) + return out + + def edit_config( + self, candidate=None, commit=True, replace=None, comment=None + ): + resp = {} + operations = self.get_device_operations() + self.check_edit_config_capability( + operations, candidate, commit, replace, comment + ) + + results = [] + requests = [] + self.send_command("configure") + for cmd in to_list(candidate): + if not isinstance(cmd, Mapping): + cmd = {"command": cmd} + + results.append(self.send_command(**cmd)) + requests.append(cmd["command"]) + out = self.get("compare") + out = to_text(out, errors="surrogate_or_strict") + diff_config = out if not out.startswith("No changes") else None + + if diff_config: + if commit: + try: + self.commit(comment) + except AnsibleConnectionFailure as e: + msg = "commit failed: %s" % e.message + self.discard_changes() + raise AnsibleConnectionFailure(msg) + else: + self.send_command("exit") + else: + self.discard_changes() + else: + self.send_command("exit") + if ( + to_text( + self._connection.get_prompt(), errors="surrogate_or_strict" + ) + .strip() + .endswith("#") + ): + self.discard_changes() + + if diff_config: + resp["diff"] = diff_config + resp["response"] = results + resp["request"] = requests + return resp + + def get( + self, + command=None, + prompt=None, + answer=None, + sendonly=False, + output=None, + newline=True, + check_all=False, + ): + if not command: + raise ValueError("must provide value of command to execute") + if output: + raise ValueError( + "'output' value %s is not supported for get" % output + ) + + return self.send_command( + command=command, + prompt=prompt, + answer=answer, + sendonly=sendonly, + newline=newline, + check_all=check_all, + ) + + def commit(self, comment=None): + if comment: + command = 'commit comment "{0}"'.format(comment) + else: + command = "commit" + self.send_command(command) + + def discard_changes(self): + self.send_command("exit discard") + + def get_diff( + self, + candidate=None, + running=None, + diff_match="line", + diff_ignore_lines=None, + path=None, + diff_replace=None, + ): + diff = {} + device_operations = self.get_device_operations() + option_values = self.get_option_values() + + if candidate is None and device_operations["supports_generate_diff"]: + raise ValueError( + "candidate configuration is required to generate diff" + ) + + if diff_match not in option_values["diff_match"]: + raise ValueError( + "'match' value %s in invalid, valid values are %s" + % (diff_match, ", ".join(option_values["diff_match"])) + ) + + if diff_replace: + raise ValueError("'replace' in diff is not supported") + + if diff_ignore_lines: + raise ValueError("'diff_ignore_lines' in diff is not supported") + + if path: + raise ValueError("'path' in diff is not supported") + + set_format = candidate.startswith("set") or candidate.startswith( + "delete" + ) + candidate_obj = NetworkConfig(indent=4, contents=candidate) + if not set_format: + config = [c.line for c in candidate_obj.items] + commands = list() + # this filters out less specific lines + for item in config: + for index, entry in enumerate(commands): + if item.startswith(entry): + del commands[index] + break + commands.append(item) + + candidate_commands = [ + "set %s" % cmd.replace(" {", "") for cmd in commands + ] + + else: + candidate_commands = str(candidate).strip().split("\n") + + if diff_match == "none": + diff["config_diff"] = list(candidate_commands) + return diff + + running_commands = [ + str(c).replace("'", "") for c in running.splitlines() + ] + + updates = list() + visited = set() + + for line in candidate_commands: + item = str(line).replace("'", "") + + if not item.startswith("set") and not item.startswith("delete"): + raise ValueError( + "line must start with either `set` or `delete`" + ) + + elif item.startswith("set") and item not in running_commands: + updates.append(line) + + elif item.startswith("delete"): + if not running_commands: + updates.append(line) + else: + item = re.sub(r"delete", "set", item) + for entry in running_commands: + if entry.startswith(item) and line not in visited: + updates.append(line) + visited.add(line) + + diff["config_diff"] = list(updates) + return diff + + def run_commands(self, commands=None, check_rc=True): + if commands is None: + raise ValueError("'commands' value is required") + + responses = list() + for cmd in to_list(commands): + if not isinstance(cmd, Mapping): + cmd = {"command": cmd} + + output = cmd.pop("output", None) + if output: + raise ValueError( + "'output' value %s is not supported for run_commands" + % output + ) + + try: + out = self.send_command(**cmd) + except AnsibleConnectionFailure as e: + if check_rc: + raise + out = getattr(e, "err", e) + + responses.append(out) + + return responses + + def get_device_operations(self): + return { + "supports_diff_replace": False, + "supports_commit": True, + "supports_rollback": False, + "supports_defaults": False, + "supports_onbox_diff": True, + "supports_commit_comment": True, + "supports_multiline_delimiter": False, + "supports_diff_match": True, + "supports_diff_ignore_lines": False, + "supports_generate_diff": False, + "supports_replace": False, + } + + def get_option_values(self): + return { + "format": ["text", "set"], + "diff_match": ["line", "none"], + "diff_replace": [], + "output": [], + } + + def get_capabilities(self): + result = super(Cliconf, self).get_capabilities() + result["rpc"] += [ + "commit", + "discard_changes", + "get_diff", + "run_commands", + ] + result["device_operations"] = self.get_device_operations() + result.update(self.get_option_values()) + return json.dumps(result) + + def set_cli_prompt_context(self): + """ + Make sure we are in the operational cli mode + :return: None + """ + if self._connection.connected: + self._update_cli_prompt_context( + config_context="#", exit_command="exit discard" + ) diff --git a/plugins/doc_fragments/__init__.py b/plugins/doc_fragments/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/doc_fragments/vyos.py b/plugins/doc_fragments/vyos.py new file mode 100644 index 0000000..094963f --- /dev/null +++ b/plugins/doc_fragments/vyos.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- + +# Copyright: (c) 2015, Peter Sprygada +# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) + + +class ModuleDocFragment(object): + + # Standard files documentation fragment + DOCUMENTATION = r"""options: + provider: + description: + - B(Deprecated) + - 'Starting with Ansible 2.5 we recommend using C(connection: network_cli).' + - For more information please see the L(Network Guide, ../network/getting_started/network_differences.html#multiple-communication-protocols). + - HORIZONTALLINE + - A dict object containing connection details. + type: dict + suboptions: + host: + description: + - Specifies the DNS host name or address for connecting to the remote device + over the specified transport. The value of host is used as the destination + address for the transport. + type: str + required: true + port: + description: + - Specifies the port to use when building the connection to the remote device. + type: int + default: 22 + username: + description: + - Configures the username to use to authenticate the connection to the remote + device. This value is used to authenticate the SSH session. If the value + is not specified in the task, the value of environment variable C(ANSIBLE_NET_USERNAME) + will be used instead. + type: str + password: + description: + - Specifies the password to use to authenticate the connection to the remote + device. This value is used to authenticate the SSH session. If the value + is not specified in the task, the value of environment variable C(ANSIBLE_NET_PASSWORD) + will be used instead. + type: str + timeout: + description: + - Specifies the timeout in seconds for communicating with the network device + for either connecting or sending commands. If the timeout is exceeded before + the operation is completed, the module will error. + type: int + default: 10 + ssh_keyfile: + description: + - Specifies the SSH key to use to authenticate the connection to the remote + device. This value is the path to the key used to authenticate the SSH + session. If the value is not specified in the task, the value of environment + variable C(ANSIBLE_NET_SSH_KEYFILE) will be used instead. + type: path +notes: +- For more information on using Ansible to manage network devices see the :ref:`Ansible + Network Guide ` +""" diff --git a/plugins/module_utils/__init__.py b/plugins/module_utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/plugins/module_utils/network/vyos/config/interfaces/interfaces.py b/plugins/module_utils/network/vyos/config/interfaces/interfaces.py index d781fd0..deb504c 100644 --- a/plugins/module_utils/network/vyos/config/interfaces/interfaces.py +++ b/plugins/module_utils/network/vyos/config/interfaces/interfaces.py @@ -1,328 +1,333 @@ # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The vyos_interfaces 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.module_utils.network.common.cfg.base import ConfigBase -from ansible.module_utils.network.common.utils import ( +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 ( to_list, dict_diff, remove_empties, ) from ansible.module_utils.six import iteritems 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 ( search_obj_in_list, get_interface_type, dict_delete, ) class Interfaces(ConfigBase): """ The vyos_interfaces class """ - gather_subset = ["!all", "!min"] + gather_subset = [ + "!all", + "!min", + ] gather_network_resources = ["interfaces"] def __init__(self, module): super(Interfaces, self).__init__(module) def get_interfaces_facts(self): """ 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 ) interfaces_facts = facts["ansible_network_resources"].get("interfaces") if not interfaces_facts: return [] return interfaces_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {"changed": False} commands = list() warnings = list() existing_interfaces_facts = self.get_interfaces_facts() commands.extend(self.set_config(existing_interfaces_facts)) if commands: if self._module.check_mode: resp = self._connection.edit_config(commands, commit=False) else: resp = self._connection.edit_config(commands) result["changed"] = True result["commands"] = commands if self._module._diff: result["diff"] = resp["diff"] if result["changed"] else None changed_interfaces_facts = self.get_interfaces_facts() result["before"] = existing_interfaces_facts if result["changed"]: result["after"] = changed_interfaces_facts result["warnings"] = warnings return result def set_config(self, existing_interfaces_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_interfaces_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 = [] state = self._module.params["state"] if state in ("merged", "replaced", "overridden") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state ) ) if state == "overridden": commands.extend(self._state_overridden(want=want, have=have)) elif state == "deleted": if not want: for intf in have: commands.extend( self._state_deleted({"name": intf["name"]}, intf) ) else: for item in want: obj_in_have = search_obj_in_list(item["name"], have) commands.extend(self._state_deleted(item, obj_in_have)) else: for item in want: name = item["name"] obj_in_have = search_obj_in_list(name, have) if not obj_in_have: obj_in_have = {"name": item["name"]} elif state == "merged": commands.extend(self._state_merged(item, obj_in_have)) elif state == "replaced": commands.extend(self._state_replaced(item, obj_in_have)) return commands 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: commands.extend(self._state_deleted(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 = [] for intf in have: intf_in_want = search_obj_in_list(intf["name"], want) if not intf_in_want: commands.extend( self._state_deleted({"name": intf["name"]}, intf) ) for intf in want: intf_in_have = search_obj_in_list(intf["name"], have) commands.extend(self._state_replaced(intf, intf_in_have)) return commands def _state_merged(self, want, have): """ The command generator when state is merged :rtype: A list :returns: the commands necessary to merge the provided into the current configuration """ commands = [] want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(have) want_vifs = want_copy.pop("vifs", []) have_vifs = have_copy.pop("vifs", []) updates = dict_diff(have_copy, want_copy) if updates: for key, value in iteritems(updates): commands.append( self._compute_commands( key=key, value=value, interface=want_copy["name"] ) ) if want_vifs: for want_vif in want_vifs: have_vif = search_obj_in_list( want_vif["vlan_id"], have_vifs, key="vlan_id" ) if not have_vif: have_vif = { "vlan_id": want_vif["vlan_id"], "enabled": True, } vif_updates = dict_diff(have_vif, want_vif) if vif_updates: for key, value in iteritems(vif_updates): commands.append( self._compute_commands( key=key, value=value, interface=want_copy["name"], vif=want_vif["vlan_id"], ) ) 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 = [] want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(have) want_vifs = want_copy.pop("vifs", []) have_vifs = have_copy.pop("vifs", []) for key in dict_delete(have_copy, want_copy).keys(): if key == "enabled": continue commands.append( self._compute_commands( key=key, interface=want_copy["name"], remove=True ) ) if have_copy["enabled"] is False: commands.append( self._compute_commands( key="enabled", value=True, interface=want_copy["name"] ) ) if have_vifs: for have_vif in have_vifs: want_vif = search_obj_in_list( have_vif["vlan_id"], want_vifs, key="vlan_id" ) if not want_vif: want_vif = { "vlan_id": have_vif["vlan_id"], "enabled": True, } for key in dict_delete(have_vif, want_vif).keys(): if key == "enabled": continue commands.append( self._compute_commands( key=key, interface=want_copy["name"], vif=want_vif["vlan_id"], remove=True, ) ) if have_vif["enabled"] is False: commands.append( self._compute_commands( key="enabled", value=True, interface=want_copy["name"], vif=want_vif["vlan_id"], ) ) return commands def _compute_commands( self, interface, key, vif=None, value=None, remove=False ): intf_context = "interfaces {0} {1}".format( get_interface_type(interface), interface ) set_cmd = "set {0}".format(intf_context) del_cmd = "delete {0}".format(intf_context) if vif: set_cmd = set_cmd + (" vif {0}".format(vif)) del_cmd = del_cmd + (" vif {0}".format(vif)) if key == "enabled": if not value: command = "{0} disable".format(set_cmd) else: command = "{0} disable".format(del_cmd) else: if not remove: command = "{0} {1} '{2}'".format(set_cmd, key, value) else: command = "{0} {1}".format(del_cmd, key) return command diff --git a/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py index fb7dbdc..a23e417 100644 --- a/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/vyos/config/l3_interfaces/l3_interfaces.py @@ -1,312 +1,322 @@ # # -*- 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_l3_interfaces 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.module_utils.network.common.cfg.base import ConfigBase -from ansible.module_utils.network.common.utils import to_list, remove_empties +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 ( + to_list, + remove_empties, +) from ansible.module_utils.six import iteritems 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 ( search_obj_in_list, get_interface_type, diff_list_of_dicts, ) class L3_interfaces(ConfigBase): """ The vyos_l3_interfaces class """ - gather_subset = ["!all", "!min"] + gather_subset = [ + "!all", + "!min", + ] - gather_network_resources = ["l3_interfaces"] + gather_network_resources = [ + "l3_interfaces", + ] def __init__(self, module): super(L3_interfaces, self).__init__(module) def get_l3_interfaces_facts(self): """ 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 ) l3_interfaces_facts = facts["ansible_network_resources"].get( "l3_interfaces" ) if not l3_interfaces_facts: return [] return l3_interfaces_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {"changed": False} warnings = list() commands = list() existing_l3_interfaces_facts = self.get_l3_interfaces_facts() commands.extend(self.set_config(existing_l3_interfaces_facts)) if commands: if self._module.check_mode: resp = self._connection.edit_config(commands, commit=False) else: resp = self._connection.edit_config(commands) result["changed"] = True result["commands"] = commands if self._module._diff: result["diff"] = resp["diff"] if result["changed"] else None changed_l3_interfaces_facts = self.get_l3_interfaces_facts() result["before"] = existing_l3_interfaces_facts if result["changed"]: result["after"] = changed_l3_interfaces_facts result["warnings"] = warnings return result def set_config(self, existing_l3_interfaces_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_l3_interfaces_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 = [] state = self._module.params["state"] if state in ("merged", "replaced", "overridden") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state ) ) if state == "overridden": commands.extend(self._state_overridden(want=want, have=have)) elif state == "deleted": if not want: for intf in have: commands.extend( self._state_deleted({"name": intf["name"]}, intf) ) else: for item in want: obj_in_have = search_obj_in_list(item["name"], have) commands.extend(self._state_deleted(item, obj_in_have)) else: for item in want: name = item["name"] obj_in_have = search_obj_in_list(name, have) if not obj_in_have: obj_in_have = {"name": item["name"]} if state == "merged": commands.extend(self._state_merged(item, obj_in_have)) elif state == "replaced": commands.extend(self._state_replaced(item, obj_in_have)) return commands 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: commands.extend(self._state_deleted(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 = [] for intf in have: intf_in_want = search_obj_in_list(intf["name"], want) if not intf_in_want: commands.extend( self._state_deleted({"name": intf["name"]}, intf) ) for intf in want: intf_in_have = search_obj_in_list(intf["name"], have) commands.extend(self._state_replaced(intf, intf_in_have)) return commands def _state_merged(self, want, have): """ The command generator when state is merged :rtype: A list :returns: the commands necessary to merge the provided into the current configuration """ commands = [] want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(remove_empties(have)) want_vifs = want_copy.pop("vifs", []) have_vifs = have_copy.pop("vifs", []) for update in self._get_updates(want_copy, have_copy): for key, value in iteritems(update): commands.append( self._compute_commands( key=key, value=value, interface=want_copy["name"] ) ) if want_vifs: for want_vif in want_vifs: have_vif = search_obj_in_list( want_vif["vlan_id"], have_vifs, key="vlan_id" ) if not have_vif: have_vif = {} for update in self._get_updates(want_vif, have_vif): for key, value in iteritems(update): commands.append( self._compute_commands( key=key, value=value, interface=want_copy["name"], vif=want_vif["vlan_id"], ) ) 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 = [] want_copy = deepcopy(remove_empties(want)) have_copy = deepcopy(have) want_vifs = want_copy.pop("vifs", []) have_vifs = have_copy.pop("vifs", []) for update in self._get_updates(have_copy, want_copy): for key, value in iteritems(update): commands.append( self._compute_commands( key=key, value=value, interface=want_copy["name"], remove=True, ) ) if have_vifs: for have_vif in have_vifs: want_vif = search_obj_in_list( have_vif["vlan_id"], want_vifs, key="vlan_id" ) if not want_vif: want_vif = {"vlan_id": have_vif["vlan_id"]} for update in self._get_updates(have_vif, want_vif): for key, value in iteritems(update): commands.append( self._compute_commands( key=key, interface=want_copy["name"], value=value, vif=want_vif["vlan_id"], remove=True, ) ) return commands def _compute_commands( self, interface, key, vif=None, value=None, remove=False ): intf_context = "interfaces {0} {1}".format( get_interface_type(interface), interface ) set_cmd = "set {0}".format(intf_context) del_cmd = "delete {0}".format(intf_context) if vif: set_cmd = set_cmd + (" vif {0}".format(vif)) del_cmd = del_cmd + (" vif {0}".format(vif)) if remove: command = "{0} {1} '{2}'".format(del_cmd, key, value) else: command = "{0} {1} '{2}'".format(set_cmd, key, value) return command def _get_updates(self, want, have): updates = [] updates = diff_list_of_dicts( want.get("ipv4", []), have.get("ipv4", []) ) updates.extend( diff_list_of_dicts(want.get("ipv6", []), have.get("ipv6", [])) ) return updates diff --git a/plugins/module_utils/network/vyos/config/lag_interfaces/lag_interfaces.py b/plugins/module_utils/network/vyos/config/lag_interfaces/lag_interfaces.py index 290f3b3..2a9efd9 100644 --- a/plugins/module_utils/network/vyos/config/lag_interfaces/lag_interfaces.py +++ b/plugins/module_utils/network/vyos/config/lag_interfaces/lag_interfaces.py @@ -1,436 +1,446 @@ # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The vyos_lag_interfaces 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 ansible.module_utils.network.common.cfg.base import ConfigBase +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import ( + ConfigBase, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import ( Facts, ) -from ansible.module_utils.network.common.utils import to_list, dict_diff +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, + dict_diff, +) from ansible.module_utils.six import iteritems from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import ( search_obj_in_list, get_lst_diff_for_dicts, list_diff_want_only, list_diff_have_only, ) class Lag_interfaces(ConfigBase): """ The vyos_lag_interfaces class """ - gather_subset = ["!all", "!min"] + gather_subset = [ + "!all", + "!min", + ] - gather_network_resources = ["lag_interfaces"] + gather_network_resources = [ + "lag_interfaces", + ] params = [ "arp_monitor", "hash_policy", "members", "mode", "name", "primary", ] def __init__(self, module): super(Lag_interfaces, self).__init__(module) def get_lag_interfaces_facts(self): """ 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 ) lag_interfaces_facts = facts["ansible_network_resources"].get( "lag_interfaces" ) if not lag_interfaces_facts: return [] return lag_interfaces_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {"changed": False} commands = list() warnings = list() existing_lag_interfaces_facts = self.get_lag_interfaces_facts() commands.extend(self.set_config(existing_lag_interfaces_facts)) if commands: if self._module.check_mode: resp = self._connection.edit_config(commands, commit=False) else: resp = self._connection.edit_config(commands) result["changed"] = True result["commands"] = commands if self._module._diff: result["diff"] = resp["diff"] if result["changed"] else None changed_lag_interfaces_facts = self.get_lag_interfaces_facts() result["before"] = existing_lag_interfaces_facts if result["changed"]: result["after"] = changed_lag_interfaces_facts result["warnings"] = warnings return result def set_config(self, existing_lag_interfaces_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_lag_interfaces_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 = [] state = self._module.params["state"] if state in ("merged", "replaced", "overridden") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state ) ) if state == "overridden": commands.extend(self._state_overridden(want, have)) elif state == "deleted": if want: for want_item in want: name = want_item["name"] obj_in_have = search_obj_in_list(name, have) commands.extend(self._state_deleted(obj_in_have)) else: for have_item in have: commands.extend(self._state_deleted(have_item)) else: for want_item in want: name = want_item["name"] obj_in_have = search_obj_in_list(name, have) if state == "merged": commands.extend(self._state_merged(want_item, obj_in_have)) elif state == "replaced": commands.extend( self._state_replaced(want_item, obj_in_have) ) return commands 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: commands.extend(self._render_del_commands(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 = [] for have_item in have: lag_name = have_item["name"] obj_in_want = search_obj_in_list(lag_name, want) if not obj_in_want: commands.extend(self._purge_attribs(have_item)) for want_item in want: name = want_item["name"] obj_in_have = search_obj_in_list(name, have) commands.extend(self._state_replaced(want_item, obj_in_have)) return commands def _state_merged(self, want, have): """ 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, 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 have: commands.extend(self._purge_attribs(have)) return commands def _render_updates(self, want, have): commands = [] temp_have_members = have.pop("members", None) temp_want_members = want.pop("members", None) updates = dict_diff(have, want) if temp_have_members: have["members"] = temp_have_members if temp_want_members: want["members"] = temp_want_members commands.extend(self._add_bond_members(want, have)) if updates: for key, value in iteritems(updates): if value: if key == "arp_monitor": commands.extend( self._add_arp_monitor(updates, key, want, have) ) else: commands.append( self._compute_command( have["name"], key, str(value) ) ) return commands def _render_set_commands(self, want): commands = [] have = [] params = Lag_interfaces.params for attrib in params: value = want[attrib] if value: if attrib == "arp_monitor": commands.extend( self._add_arp_monitor(want, attrib, want, have) ) elif attrib == "members": commands.extend(self._add_bond_members(want, have)) elif attrib != "name": commands.append( self._compute_command( want["name"], attrib, value=str(value) ) ) return commands def _purge_attribs(self, have): commands = [] for item in Lag_interfaces.params: if have.get(item): if item == "members": commands.extend(self._delete_bond_members(have)) elif item != "name": commands.append( self._compute_command( have["name"], attrib=item, remove=True ) ) return commands def _render_del_commands(self, want, have): commands = [] params = Lag_interfaces.params for attrib in params: if attrib == "members": commands.extend(self._update_bond_members(attrib, want, have)) elif attrib == "arp_monitor": commands.extend(self._update_arp_monitor(attrib, want, have)) elif have.get(attrib) and not want.get(attrib): commands.append( self._compute_command(have["name"], attrib, remove=True) ) return commands def _add_bond_members(self, want, have): commands = [] diff_members = get_lst_diff_for_dicts(want, have, "members") if diff_members: for key in diff_members: commands.append( self._compute_command( key["member"], "bond-group", want["name"], type="ethernet", ) ) return commands def _add_arp_monitor(self, updates, key, want, have): commands = [] arp_monitor = updates.get(key) or {} diff_targets = self._get_arp_monitor_target_diff( want, have, key, "target" ) if "interval" in arp_monitor: commands.append( self._compute_command( key=want["name"] + " arp-monitor", attrib="interval", value=str(arp_monitor["interval"]), ) ) if diff_targets: for target in diff_targets: commands.append( self._compute_command( key=want["name"] + " arp-monitor", attrib="target", value=target, ) ) return commands def _delete_bond_members(self, have): commands = [] for member in have["members"]: commands.append( self._compute_command( member["member"], "bond-group", have["name"], remove=True, type="ethernet", ) ) return commands def _update_arp_monitor(self, key, want, have): commands = [] want_arp_target = [] have_arp_target = [] want_arp_monitor = want.get(key) or {} have_arp_monitor = have.get(key) or {} if want_arp_monitor and "target" in want_arp_monitor: want_arp_target = want_arp_monitor["target"] if have_arp_monitor and "target" in have_arp_monitor: have_arp_target = have_arp_monitor["target"] if "interval" in have_arp_monitor and not want_arp_monitor: commands.append( self._compute_command( key=have["name"] + " arp-monitor", attrib="interval", remove=True, ) ) if "target" in have_arp_monitor: target_diff = list_diff_have_only(want_arp_target, have_arp_target) if target_diff: for target in target_diff: commands.append( self._compute_command( key=have["name"] + " arp-monitor", attrib="target", value=target, remove=True, ) ) return commands def _update_bond_members(self, key, want, have): commands = [] want_members = want.get(key) or [] have_members = have.get(key) or [] members_diff = list_diff_have_only(want_members, have_members) if members_diff: for member in members_diff: commands.append( self._compute_command( member["member"], "bond-group", have["name"], True, "ethernet", ) ) return commands def _get_arp_monitor_target_diff( self, want_list, have_list, dict_name, lst ): want_arp_target = [] have_arp_target = [] want_arp_monitor = want_list.get(dict_name) or {} if want_arp_monitor and lst in want_arp_monitor: want_arp_target = want_arp_monitor[lst] if not have_list: diff = want_arp_target else: have_arp_monitor = have_list.get(dict_name) or {} if have_arp_monitor and lst in have_arp_monitor: have_arp_target = have_arp_monitor[lst] diff = list_diff_want_only(want_arp_target, have_arp_target) return diff def _compute_command( self, key, attrib, value=None, remove=False, type="bonding" ): if remove: cmd = "delete interfaces " + type else: cmd = "set interfaces " + type cmd += " " + key if attrib == "arp_monitor": attrib = "arp-monitor" elif attrib == "hash_policy": attrib = "hash-policy" cmd += " " + attrib if value: cmd += " '" + value + "'" return cmd diff --git a/plugins/module_utils/network/vyos/config/lldp_global/lldp_global.py b/plugins/module_utils/network/vyos/config/lldp_global/lldp_global.py index 303d46a..010e96d 100644 --- a/plugins/module_utils/network/vyos/config/lldp_global/lldp_global.py +++ b/plugins/module_utils/network/vyos/config/lldp_global/lldp_global.py @@ -1,254 +1,264 @@ # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The vyos_lldp_global 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 ansible.module_utils.network.common.cfg.base import ConfigBase -from ansible.module_utils.network.common.utils import to_list, dict_diff +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 ( + to_list, + dict_diff, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import ( Facts, ) from ansible.module_utils.six import iteritems from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import ( get_lst_diff_for_dicts, list_diff_have_only, ) class Lldp_global(ConfigBase): """ The vyos_lldp_global class """ - gather_subset = ["!all", "!min"] + gather_subset = [ + "!all", + "!min", + ] - gather_network_resources = ["lldp_global"] + gather_network_resources = [ + "lldp_global", + ] params = ["enable", "address", "snmp", "legacy_protocols"] def __init__(self, module): super(Lldp_global, self).__init__(module) def get_lldp_global_facts(self): """ 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 ) lldp_global_facts = facts["ansible_network_resources"].get( "lldp_global" ) if not lldp_global_facts: return {} return lldp_global_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {"changed": False} commands = list() warnings = list() existing_lldp_global_facts = self.get_lldp_global_facts() commands.extend(self.set_config(existing_lldp_global_facts)) if commands: if not self._module.check_mode: self._connection.edit_config(commands) result["changed"] = True result["commands"] = commands changed_lldp_global_facts = self.get_lldp_global_facts() result["before"] = existing_lldp_global_facts if result["changed"]: result["after"] = changed_lldp_global_facts result["warnings"] = warnings return result def set_config(self, existing_lldp_global_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_lldp_global_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 = [] state = self._module.params["state"] if state in ("merged", "replaced") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state ) ) if state == "deleted": commands.extend(self._state_deleted(want=None, have=have)) elif state == "merged": commands.extend(self._state_merged(want=want, have=have)) elif state == "replaced": commands.extend(self._state_replaced(want=want, have=have)) return commands 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: commands.extend(self._state_deleted(want, have)) commands.extend(self._state_merged(want, have)) return commands def _state_merged(self, want, have): """ The command generator when state is merged :rtype: A list :returns: the commands necessary to merge the provided into the current configuration """ commands = [] commands.extend(self._render_updates(want, have)) 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: for item in Lldp_global.params: if item == "legacy_protocols": commands.extend(self._update_lldp_protocols(want, have)) elif ( have.get(item) and not want.get(item) and item != "enable" ): commands.append(Lldp_global.del_cmd + item) elif have: for item in Lldp_global.params: if have.get(item): if item == "legacy_protocols": commands.append( self._compute_command( "legacy-protocols", remove=True ) ) elif item == "address": commands.append( self._compute_command( "management-address", remove=True ) ) elif item == "snmp": commands.append( self._compute_command(item, remove=True) ) return commands def _render_updates(self, want, have): commands = [] if have: temp_have_legacy_protos = have.pop("legacy_protocols", None) else: have = {} temp_want_legacy_protos = want.pop("legacy_protocols", None) updates = dict_diff(have, want) if have and temp_have_legacy_protos: have["legacy_protocols"] = temp_have_legacy_protos if not have and temp_want_legacy_protos: want["legacy_protocols"] = temp_want_legacy_protos commands.extend(self._add_lldp_protocols(want, have)) if updates: for key, value in iteritems(updates): if value: if key == "enable": commands.append(self._compute_command()) elif key == "address": commands.append( self._compute_command( "management-address", str(value) ) ) elif key == "snmp": if value == "disable": commands.append( self._compute_command(key, remove=True) ) else: commands.append( self._compute_command(key, str(value)) ) return commands def _add_lldp_protocols(self, want, have): commands = [] diff_members = get_lst_diff_for_dicts(want, have, "legacy_protocols") for key in diff_members: commands.append(self._compute_command("legacy-protocols", key)) return commands def _update_lldp_protocols(self, want_item, have_item): commands = [] want_protocols = want_item.get("legacy_protocols") or [] have_protocols = have_item.get("legacy_protocols") or [] members_diff = list_diff_have_only(want_protocols, have_protocols) if members_diff: for member in members_diff: commands.append( self._compute_command( "legacy-protocols", member, remove=True ) ) return commands def _compute_command(self, key=None, value=None, remove=False): if remove: cmd = "delete service lldp" else: cmd = "set service lldp" if key: cmd += " " + key if value: cmd += " '" + value + "'" return cmd diff --git a/plugins/module_utils/network/vyos/config/lldp_interfaces/lldp_interfaces.py b/plugins/module_utils/network/vyos/config/lldp_interfaces/lldp_interfaces.py index aa0bd36..377fec9 100644 --- a/plugins/module_utils/network/vyos/config/lldp_interfaces/lldp_interfaces.py +++ b/plugins/module_utils/network/vyos/config/lldp_interfaces/lldp_interfaces.py @@ -1,428 +1,438 @@ # # -*- 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_lldp_interfaces 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 ansible.module_utils.network.common.cfg.base import ConfigBase +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import ( + ConfigBase, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import ( Facts, ) -from ansible.module_utils.network.common.utils import to_list, dict_diff +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + to_list, + dict_diff, +) from ansible.module_utils.six import iteritems -from ansible.module_utils.network.vyos.utils.utils import ( +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.utils.utils import ( search_obj_in_list, search_dict_tv_in_list, key_value_in_dict, is_dict_element_present, ) class Lldp_interfaces(ConfigBase): """ The vyos_lldp_interfaces class """ - gather_subset = ["!all", "!min"] + gather_subset = [ + "!all", + "!min", + ] - gather_network_resources = ["lldp_interfaces"] + gather_network_resources = [ + "lldp_interfaces", + ] params = ["enable", "location", "name"] def __init__(self, module): super(Lldp_interfaces, self).__init__(module) def get_lldp_interfaces_facts(self): """ 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 ) lldp_interfaces_facts = facts["ansible_network_resources"].get( "lldp_interfaces" ) if not lldp_interfaces_facts: return [] return lldp_interfaces_facts def execute_module(self): """ Execute the module :rtype: A dictionary :returns: The result from module execution """ result = {"changed": False} commands = list() warnings = list() existing_lldp_interfaces_facts = self.get_lldp_interfaces_facts() commands.extend(self.set_config(existing_lldp_interfaces_facts)) if commands: if self._module.check_mode: resp = self._connection.edit_config(commands, commit=False) else: resp = self._connection.edit_config(commands) result["changed"] = True result["commands"] = commands if self._module._diff: result["diff"] = resp["diff"] if result["changed"] else None changed_lldp_interfaces_facts = self.get_lldp_interfaces_facts() result["before"] = existing_lldp_interfaces_facts if result["changed"]: result["after"] = changed_lldp_interfaces_facts result["warnings"] = warnings return result def set_config(self, existing_lldp_interfaces_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_lldp_interfaces_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 = [] state = self._module.params["state"] if state in ("merged", "replaced", "overridden") and not want: self._module.fail_json( msg="value of config parameter must not be empty for state {0}".format( state ) ) if state == "overridden": commands.extend(self._state_overridden(want=want, have=have)) elif state == "deleted": if want: for item in want: name = item["name"] have_item = search_obj_in_list(name, have) commands.extend( self._state_deleted(want=None, have=have_item) ) else: for have_item in have: commands.extend( self._state_deleted(want=None, have=have_item) ) else: for want_item in want: name = want_item["name"] have_item = search_obj_in_list(name, have) if state == "merged": commands.extend( self._state_merged(want=want_item, have=have_item) ) else: commands.extend( self._state_replaced(want=want_item, have=have_item) ) return commands 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: commands.extend(self._state_deleted(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 = [] for have_item in have: lldp_name = have_item["name"] lldp_in_want = search_obj_in_list(lldp_name, want) if not lldp_in_want: commands.append( self._compute_command(have_item["name"], remove=True) ) for want_item in want: name = want_item["name"] lldp_in_have = search_obj_in_list(name, have) commands.extend(self._state_replaced(want_item, lldp_in_have)) return commands def _state_merged(self, want, have): """ 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: params = Lldp_interfaces.params for attrib in params: if attrib == "location": commands.extend( self._update_location(have["name"], want, have) ) elif have: commands.append(self._compute_command(have["name"], remove=True)) return commands def _render_updates(self, want, have): commands = [] lldp_name = have["name"] commands.extend(self._configure_status(lldp_name, want, have)) commands.extend(self._add_location(lldp_name, want, have)) return commands def _render_set_commands(self, want): commands = [] have = {} lldp_name = want["name"] params = Lldp_interfaces.params commands.extend(self._add_location(lldp_name, want, have)) for attrib in params: value = want[attrib] if value: if attrib == "location": commands.extend(self._add_location(lldp_name, want, have)) elif attrib == "enable": if not value: commands.append( self._compute_command(lldp_name, value="disable") ) else: commands.append(self._compute_command(lldp_name)) return commands def _configure_status(self, name, want_item, have_item): commands = [] if is_dict_element_present(have_item, "enable"): temp_have_item = False else: temp_have_item = True if want_item["enable"] != temp_have_item: if want_item["enable"]: commands.append( self._compute_command(name, value="disable", remove=True) ) else: commands.append(self._compute_command(name, value="disable")) return commands def _add_location(self, name, want_item, have_item): commands = [] have_dict = {} have_ca = {} set_cmd = name + " location " want_location_type = want_item.get("location") or {} have_location_type = have_item.get("location") or {} if want_location_type["coordinate_based"]: want_dict = want_location_type.get("coordinate_based") or {} if is_dict_element_present(have_location_type, "coordinate_based"): have_dict = have_location_type.get("coordinate_based") or {} location_type = "coordinate-based" updates = dict_diff(have_dict, want_dict) for key, value in iteritems(updates): if value: commands.append( self._compute_command( set_cmd + location_type, key, str(value) ) ) elif want_location_type["civic_based"]: location_type = "civic-based" want_dict = want_location_type.get("civic_based") or {} want_ca = want_dict.get("ca_info") or [] if is_dict_element_present(have_location_type, "civic_based"): have_dict = have_location_type.get("civic_based") or {} have_ca = have_dict.get("ca_info") or [] if want_dict["country_code"] != have_dict["country_code"]: commands.append( self._compute_command( set_cmd + location_type, "country-code", str(want_dict["country_code"]), ) ) else: commands.append( self._compute_command( set_cmd + location_type, "country-code", str(want_dict["country_code"]), ) ) commands.extend(self._add_civic_address(name, want_ca, have_ca)) elif want_location_type["elin"]: location_type = "elin" if is_dict_element_present(have_location_type, "elin"): if want_location_type.get("elin") != have_location_type.get( "elin" ): commands.append( self._compute_command( set_cmd + location_type, value=str(want_location_type["elin"]), ) ) else: commands.append( self._compute_command( set_cmd + location_type, value=str(want_location_type["elin"]), ) ) return commands def _update_location(self, name, want_item, have_item): commands = [] del_cmd = name + " location" want_location_type = want_item.get("location") or {} have_location_type = have_item.get("location") or {} if want_location_type["coordinate_based"]: want_dict = want_location_type.get("coordinate_based") or {} if is_dict_element_present(have_location_type, "coordinate_based"): have_dict = have_location_type.get("coordinate_based") or {} location_type = "coordinate-based" for key, value in iteritems(have_dict): only_in_have = key_value_in_dict(key, value, want_dict) if not only_in_have: commands.append( self._compute_command( del_cmd + location_type, key, str(value), True ) ) else: commands.append(self._compute_command(del_cmd, remove=True)) elif want_location_type["civic_based"]: want_dict = want_location_type.get("civic_based") or {} want_ca = want_dict.get("ca_info") or [] if is_dict_element_present(have_location_type, "civic_based"): have_dict = have_location_type.get("civic_based") or {} have_ca = have_dict.get("ca_info") commands.extend( self._update_civic_address(name, want_ca, have_ca) ) else: commands.append(self._compute_command(del_cmd, remove=True)) else: if is_dict_element_present(have_location_type, "elin"): if want_location_type.get("elin") != have_location_type.get( "elin" ): commands.append( self._compute_command(del_cmd, remove=True) ) else: commands.append(self._compute_command(del_cmd, remove=True)) return commands def _add_civic_address(self, name, want, have): commands = [] for item in want: ca_type = item["ca_type"] ca_value = item["ca_value"] obj_in_have = search_dict_tv_in_list( ca_type, ca_value, have, "ca_type", "ca_value" ) if not obj_in_have: commands.append( self._compute_command( key=name + " location civic-based ca-type", attrib=str(ca_type) + " ca-value", value=ca_value, ) ) return commands def _update_civic_address(self, name, want, have): commands = [] for item in have: ca_type = item["ca_type"] ca_value = item["ca_value"] in_want = search_dict_tv_in_list( ca_type, ca_value, want, "ca_type", "ca_value" ) if not in_want: commands.append( self._compute_command( name, "location civic-based ca-type", str(ca_type), remove=True, ) ) return commands def _compute_command(self, key, attrib=None, value=None, remove=False): if remove: cmd = "delete service lldp interface " else: cmd = "set service lldp interface " cmd += key if attrib: cmd += " " + attrib if value: cmd += " '" + value + "'" return cmd diff --git a/plugins/module_utils/network/vyos/facts/facts.py b/plugins/module_utils/network/vyos/facts/facts.py index bb292e1..b5816c2 100644 --- a/plugins/module_utils/network/vyos/facts/facts.py +++ b/plugins/module_utils/network/vyos/facts/facts.py @@ -1,74 +1,76 @@ # Copyright 2019 Red Hat # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The facts class for vyos this file validates each subset of facts and selectively calls the appropriate facts gathering function """ from __future__ import absolute_import, division, print_function __metaclass__ = type -from ansible.module_utils.network.common.facts.facts import FactsBase +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.facts.facts import ( + FactsBase, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.interfaces.interfaces import ( InterfacesFacts, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.l3_interfaces.l3_interfaces import ( L3_interfacesFacts, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.lag_interfaces.lag_interfaces import ( Lag_interfacesFacts, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.lldp_global.lldp_global import ( Lldp_globalFacts, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.lldp_interfaces.lldp_interfaces import ( Lldp_interfacesFacts, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.legacy.base import ( Default, Neighbors, Config, ) FACT_LEGACY_SUBSETS = dict(default=Default, neighbors=Neighbors, config=Config) FACT_RESOURCE_SUBSETS = dict( interfaces=InterfacesFacts, l3_interfaces=L3_interfacesFacts, lag_interfaces=Lag_interfacesFacts, lldp_global=Lldp_globalFacts, lldp_interfaces=Lldp_interfacesFacts, ) class Facts(FactsBase): """ The fact class for vyos """ VALID_LEGACY_GATHER_SUBSETS = frozenset(FACT_LEGACY_SUBSETS.keys()) VALID_RESOURCE_SUBSETS = frozenset(FACT_RESOURCE_SUBSETS.keys()) def __init__(self, module): super(Facts, self).__init__(module) def get_facts( self, legacy_facts_type=None, resource_facts_type=None, data=None ): """ Collect the facts for vyos :param legacy_facts_type: List of legacy facts types :param resource_facts_type: List of resource fact types :param data: previously collected conf :rtype: dict :return: the facts gathered """ if self.VALID_RESOURCE_SUBSETS: self.get_network_resources_facts( FACT_RESOURCE_SUBSETS, resource_facts_type, data ) if self.VALID_LEGACY_GATHER_SUBSETS: self.get_network_legacy_facts( FACT_LEGACY_SUBSETS, legacy_facts_type ) return self.ansible_facts, self._warnings diff --git a/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py b/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py index 7b73b9b..4b24803 100644 --- a/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py +++ b/plugins/module_utils/network/vyos/facts/interfaces/interfaces.py @@ -1,132 +1,134 @@ # # -*- 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 interfaces 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 re import findall, M from copy import deepcopy -from ansible.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.interfaces.interfaces import ( InterfacesArgs, ) class InterfacesFacts(object): """ The vyos interfaces fact class """ def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = InterfacesArgs.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 populate_facts(self, connection, ansible_facts, data=None): """ Populate the facts for interfaces :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ if not data: data = connection.get_config(flags=["| grep interfaces"]) objs = [] interface_names = findall( r"^set interfaces (?:ethernet|bonding|vti|loopback|vxlan) (?:\'*)(\S+)(?:\'*)", data, M, ) if interface_names: for interface in set(interface_names): intf_regex = r" %s .+$" % interface.strip("'") cfg = findall(intf_regex, data, M) obj = self.render_config(cfg) obj["name"] = interface.strip("'") if obj: objs.append(obj) facts = {} if objs: facts["interfaces"] = [] params = utils.validate_config( self.argument_spec, {"config": objs} ) for cfg in params["config"]: facts["interfaces"].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 """ vif_conf = "\n".join(filter(lambda x: ("vif" in x), conf)) eth_conf = "\n".join(filter(lambda x: ("vif" not in x), conf)) config = self.parse_attribs( ["description", "speed", "mtu", "duplex"], eth_conf ) config["vifs"] = self.parse_vifs(vif_conf) return utils.remove_empties(config) def parse_vifs(self, conf): vif_names = findall(r"vif (?:\'*)(\d+)(?:\'*)", conf, M) vifs_list = None if vif_names: vifs_list = [] for vif in set(vif_names): vif_regex = r" %s .+$" % vif cfg = "\n".join(findall(vif_regex, conf, M)) obj = self.parse_attribs(["description", "mtu"], cfg) obj["vlan_id"] = int(vif) if obj: vifs_list.append(obj) vifs_list = sorted(vifs_list, key=lambda i: i["vlan_id"]) return vifs_list def parse_attribs(self, attribs, conf): config = {} for item in attribs: value = utils.parse_conf_arg(conf, item) if value and item == "mtu": config[item] = int(value.strip("'")) elif value: config[item] = value.strip("'") else: config[item] = None if "disable" in conf: config["enabled"] = False else: config["enabled"] = True return utils.remove_empties(config) diff --git a/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py index 05973ba..babfc85 100644 --- a/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py +++ b/plugins/module_utils/network/vyos/facts/l3_interfaces/l3_interfaces.py @@ -1,139 +1,141 @@ # # -*- 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 l3_interfaces 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 import re from copy import deepcopy -from ansible.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible.module_utils.six import iteritems from ansible.module_utils.compat import ipaddress from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.l3_interfaces.l3_interfaces import ( L3_interfacesArgs, ) class L3_interfacesFacts(object): """ The vyos l3_interfaces fact class """ def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = L3_interfacesArgs.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 populate_facts(self, connection, ansible_facts, data=None): """ Populate the facts for l3_interfaces :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ if not data: data = connection.get_config() # operate on a collection of resource x objs = [] interface_names = re.findall( r"set interfaces (?:ethernet|bonding|vti|vxlan) (?:\'*)(\S+)(?:\'*)", data, re.M, ) if interface_names: for interface in set(interface_names): intf_regex = r" %s .+$" % interface cfg = re.findall(intf_regex, data, re.M) obj = self.render_config(cfg) obj["name"] = interface.strip("'") if obj: objs.append(obj) ansible_facts["ansible_network_resources"].pop("l3_interfaces", None) facts = {} if objs: facts["l3_interfaces"] = [] params = utils.validate_config( self.argument_spec, {"config": objs} ) for cfg in params["config"]: facts["l3_interfaces"].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 """ vif_conf = "\n".join(filter(lambda x: ("vif" in x), conf)) eth_conf = "\n".join(filter(lambda x: ("vif" not in x), conf)) config = self.parse_attribs(eth_conf) config["vifs"] = self.parse_vifs(vif_conf) return utils.remove_empties(config) def parse_vifs(self, conf): vif_names = re.findall(r"vif (\d+)", conf, re.M) vifs_list = None if vif_names: vifs_list = [] for vif in set(vif_names): vif_regex = r" %s .+$" % vif cfg = "\n".join(re.findall(vif_regex, conf, re.M)) obj = self.parse_attribs(cfg) obj["vlan_id"] = vif if obj: vifs_list.append(obj) return vifs_list def parse_attribs(self, conf): config = {} ipaddrs = re.findall(r"address (\S+)", conf, re.M) config["ipv4"] = [] config["ipv6"] = [] for item in ipaddrs: item = item.strip("'") if item == "dhcp": config["ipv4"].append({"address": item}) elif item == "dhcpv6": config["ipv6"].append({"address": item}) else: ip_version = ipaddress.ip_address(item.split("/")[0]).version if ip_version == 4: config["ipv4"].append({"address": item}) else: config["ipv6"].append({"address": item}) for key, value in iteritems(config): if value == []: config[key] = None return utils.remove_empties(config) diff --git a/plugins/module_utils/network/vyos/facts/lag_interfaces/lag_interfaces.py b/plugins/module_utils/network/vyos/facts/lag_interfaces/lag_interfaces.py index 6ae780f..9201e5c 100644 --- a/plugins/module_utils/network/vyos/facts/lag_interfaces/lag_interfaces.py +++ b/plugins/module_utils/network/vyos/facts/lag_interfaces/lag_interfaces.py @@ -1,150 +1,152 @@ # # -*- 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 lag_interfaces 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 re import findall, search, M from copy import deepcopy -from ansible.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.lag_interfaces.lag_interfaces import ( Lag_interfacesArgs, ) class Lag_interfacesFacts(object): """ The vyos lag_interfaces fact class """ def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = Lag_interfacesArgs.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 populate_facts(self, connection, ansible_facts, data=None): """ Populate the facts for lag_interfaces :param module: the module instance :param connection: the device connection :param data: previously collected conf :rtype: dictionary :returns: facts """ if not data: data = connection.get_config() objs = [] lag_names = findall(r"^set interfaces bonding (\S+)", data, M) if lag_names: for lag in set(lag_names): lag_regex = r" %s .+$" % lag cfg = findall(lag_regex, data, M) obj = self.render_config(cfg) output = connection.run_commands( ["show interfaces bonding " + lag + " slaves"] ) lines = output[0].splitlines() members = [] member = {} if len(lines) > 1: for line in lines[2:]: splitted_line = line.split() if len(splitted_line) > 1: member["member"] = splitted_line[0] members.append(member) else: members = [] member = {} obj["name"] = lag.strip("'") if members: obj["members"] = members if obj: objs.append(obj) facts = {} if objs: facts["lag_interfaces"] = [] params = utils.validate_config( self.argument_spec, {"config": objs} ) for cfg in params["config"]: facts["lag_interfaces"].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 """ arp_monitor_conf = "\n".join( filter(lambda x: ("arp-monitor" in x), conf) ) hash_policy_conf = "\n".join( filter(lambda x: ("hash-policy" in x), conf) ) lag_conf = "\n".join(filter(lambda x: ("bond" in x), conf)) config = self.parse_attribs(["mode", "primary"], lag_conf) config["arp_monitor"] = self.parse_arp_monitor(arp_monitor_conf) config["hash_policy"] = self.parse_hash_policy(hash_policy_conf) return utils.remove_empties(config) def parse_attribs(self, attribs, conf): config = {} for item in attribs: value = utils.parse_conf_arg(conf, item) if value: config[item] = value.strip("'") else: config[item] = None return utils.remove_empties(config) def parse_arp_monitor(self, conf): arp_monitor = None if conf: arp_monitor = {} target_list = [] interval = search(r"^.*arp-monitor interval (.+)", conf, M) targets = findall(r"^.*arp-monitor target '(.+)'", conf, M) if targets: for target in targets: target_list.append(target) arp_monitor["target"] = target_list if interval: value = interval.group(1).strip("'") arp_monitor["interval"] = int(value) return arp_monitor def parse_hash_policy(self, conf): hash_policy = None if conf: hash_policy = search(r"^.*hash-policy (.+)", conf, M) hash_policy = hash_policy.group(1).strip("'") return hash_policy diff --git a/plugins/module_utils/network/vyos/facts/legacy/base.py b/plugins/module_utils/network/vyos/facts/legacy/base.py index dce93aa..f6b343e 100644 --- a/plugins/module_utils/network/vyos/facts/legacy/base.py +++ b/plugins/module_utils/network/vyos/facts/legacy/base.py @@ -1,154 +1,162 @@ # -*- 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 interfaces 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 import platform import re -from ansible.module_utils.network.vyos.vyos import ( +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( run_commands, get_capabilities, ) class LegacyFactsBase(object): COMMANDS = frozenset() def __init__(self, module): self.module = module self.facts = dict() self.warnings = list() self.responses = None def populate(self): self.responses = run_commands(self.module, list(self.COMMANDS)) class Default(LegacyFactsBase): - COMMANDS = ["show version"] + COMMANDS = [ + "show version", + ] def populate(self): super(Default, self).populate() data = self.responses[0] self.facts["serialnum"] = self.parse_serialnum(data) self.facts.update(self.platform_facts()) def parse_serialnum(self, data): match = re.search(r"HW S/N:\s+(\S+)", data) if match: return match.group(1) def platform_facts(self): platform_facts = {} resp = get_capabilities(self.module) device_info = resp["device_info"] platform_facts["system"] = device_info["network_os"] for item in ("model", "image", "version", "platform", "hostname"): val = device_info.get("network_os_%s" % item) if val: platform_facts[item] = val platform_facts["api"] = resp["network_api"] platform_facts["python_version"] = platform.python_version() return platform_facts class Config(LegacyFactsBase): - COMMANDS = ["show configuration commands", "show system commit"] + COMMANDS = [ + "show configuration commands", + "show system commit", + ] def populate(self): super(Config, self).populate() self.facts["config"] = self.responses commits = self.responses[1] entries = list() entry = None for line in commits.split("\n"): match = re.match(r"(\d+)\s+(.+)by(.+)via(.+)", line) if match: if entry: entries.append(entry) entry = dict( revision=match.group(1), datetime=match.group(2), by=str(match.group(3)).strip(), via=str(match.group(4)).strip(), comment=None, ) else: entry["comment"] = line.strip() self.facts["commits"] = entries class Neighbors(LegacyFactsBase): - COMMANDS = ["show lldp neighbors", "show lldp neighbors detail"] + COMMANDS = [ + "show lldp neighbors", + "show lldp neighbors detail", + ] def populate(self): super(Neighbors, self).populate() all_neighbors = self.responses[0] if "LLDP not configured" not in all_neighbors: neighbors = self.parse(self.responses[1]) self.facts["neighbors"] = self.parse_neighbors(neighbors) def parse(self, data): parsed = list() values = None for line in data.split("\n"): if not line: continue elif line[0] == " ": values += "\n%s" % line elif line.startswith("Interface"): if values: parsed.append(values) values = line if values: parsed.append(values) return parsed def parse_neighbors(self, data): facts = dict() for item in data: interface = self.parse_interface(item) host = self.parse_host(item) port = self.parse_port(item) if interface not in facts: facts[interface] = list() facts[interface].append(dict(host=host, port=port)) return facts def parse_interface(self, data): match = re.search(r"^Interface:\s+(\S+),", data) return match.group(1) def parse_host(self, data): match = re.search(r"SysName:\s+(.+)$", data, re.M) if match: return match.group(1) def parse_port(self, data): match = re.search(r"PortDescr:\s+(.+)$", data, re.M) if match: return match.group(1) diff --git a/plugins/module_utils/network/vyos/facts/lldp_global/lldp_global.py b/plugins/module_utils/network/vyos/facts/lldp_global/lldp_global.py index 8954393..3c7e2f9 100644 --- a/plugins/module_utils/network/vyos/facts/lldp_global/lldp_global.py +++ b/plugins/module_utils/network/vyos/facts/lldp_global/lldp_global.py @@ -1,114 +1,116 @@ # # -*- 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 lldp_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. """ from __future__ import absolute_import, division, print_function __metaclass__ = type from re import findall, M from copy import deepcopy -from ansible.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.lldp_global.lldp_global import ( Lldp_globalArgs, ) class Lldp_globalFacts(object): """ The vyos lldp_global fact class """ def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = Lldp_globalArgs.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 populate_facts(self, connection, ansible_facts, data=None): """ Populate the facts for lldp_global :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ if not data: data = connection.get_config() objs = {} lldp_output = findall(r"^set service lldp (\S+)", data, M) if lldp_output: for item in set(lldp_output): lldp_regex = r" %s .+$" % item cfg = findall(lldp_regex, data, M) obj = self.render_config(cfg) if obj: objs.update(obj) lldp_service = findall(r"^set service (lldp)?('lldp')", data, M) if lldp_service or lldp_output: lldp_obj = {} lldp_obj["enable"] = True objs.update(lldp_obj) facts = {} params = utils.validate_config(self.argument_spec, {"config": objs}) facts["lldp_global"] = utils.remove_empties(params["config"]) 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 """ protocol_conf = "\n".join( filter(lambda x: ("legacy-protocols" in x), conf) ) att_conf = "\n".join( filter(lambda x: ("legacy-protocols" not in x), conf) ) config = self.parse_attribs(["snmp", "address"], att_conf) config["legacy_protocols"] = self.parse_protocols(protocol_conf) return utils.remove_empties(config) def parse_protocols(self, conf): protocol_support = None if conf: protocols = findall(r"^.*legacy-protocols (.+)", conf, M) if protocols: protocol_support = [] for protocol in protocols: protocol_support.append(protocol.strip("'")) return protocol_support def parse_attribs(self, attribs, conf): config = {} for item in attribs: value = utils.parse_conf_arg(conf, item) if value: config[item] = value.strip("'") else: config[item] = None return utils.remove_empties(config) diff --git a/plugins/module_utils/network/vyos/facts/lldp_interfaces/lldp_interfaces.py b/plugins/module_utils/network/vyos/facts/lldp_interfaces/lldp_interfaces.py index 72629ed..dcfbc6e 100644 --- a/plugins/module_utils/network/vyos/facts/lldp_interfaces/lldp_interfaces.py +++ b/plugins/module_utils/network/vyos/facts/lldp_interfaces/lldp_interfaces.py @@ -1,153 +1,155 @@ # # -*- 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 lldp_interfaces 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 re import findall, search, M from copy import deepcopy -from ansible.module_utils.network.common import utils +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common import ( + utils, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.lldp_interfaces.lldp_interfaces import ( Lldp_interfacesArgs, ) class Lldp_interfacesFacts(object): """ The vyos lldp_interfaces fact class """ def __init__(self, module, subspec="config", options="options"): self._module = module self.argument_spec = Lldp_interfacesArgs.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 populate_facts(self, connection, ansible_facts, data=None): """ Populate the facts for lldp_interfaces :param connection: the device connection :param ansible_facts: Facts dictionary :param data: previously collected conf :rtype: dictionary :returns: facts """ if not data: data = connection.get_config() objs = [] lldp_names = findall(r"^set service lldp interface (\S+)", data, M) if lldp_names: for lldp in set(lldp_names): lldp_regex = r" %s .+$" % lldp cfg = findall(lldp_regex, data, M) obj = self.render_config(cfg) obj["name"] = lldp.strip("'") if obj: objs.append(obj) facts = {} if objs: facts["lldp_interfaces"] = objs ansible_facts["ansible_network_resources"].update(facts) 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 """ config = {} location = {} civic_conf = "\n".join(filter(lambda x: ("civic-based" in x), conf)) elin_conf = "\n".join(filter(lambda x: ("elin" in x), conf)) coordinate_conf = "\n".join( filter(lambda x: ("coordinate-based" in x), conf) ) disable = "\n".join(filter(lambda x: ("disable" in x), conf)) coordinate_based_conf = self.parse_attribs( ["altitude", "datum", "longitude", "latitude"], coordinate_conf ) elin_based_conf = self.parse_lldp_elin_based(elin_conf) civic_based_conf = self.parse_lldp_civic_based(civic_conf) if disable: config["enable"] = False if coordinate_conf: location["coordinate_based"] = coordinate_based_conf config["location"] = location elif civic_based_conf: location["civic_based"] = civic_based_conf config["location"] = location elif elin_conf: location["elin"] = elin_based_conf config["location"] = location return utils.remove_empties(config) def parse_attribs(self, attribs, conf): config = {} for item in attribs: value = utils.parse_conf_arg(conf, item) if value: value = value.strip("'") if item == "altitude": value = int(value) config[item] = value else: config[item] = None return utils.remove_empties(config) def parse_lldp_civic_based(self, conf): civic_based = None if conf: civic_info_list = [] civic_add_list = findall(r"^.*civic-based ca-type (.+)", conf, M) if civic_add_list: for civic_add in civic_add_list: ca = civic_add.split(" ") c_add = {} c_add["ca_type"] = int(ca[0].strip("'")) c_add["ca_value"] = ca[2].strip("'") civic_info_list.append(c_add) country_code = search( r"^.*civic-based country-code (.+)", conf, M ) civic_based = {} civic_based["ca_info"] = civic_info_list civic_based["country_code"] = country_code.group(1).strip("'") return civic_based def parse_lldp_elin_based(self, conf): elin_based = None if conf: e_num = search(r"^.* elin (.+)", conf, M) elin_based = e_num.group(1).strip("'") return elin_based diff --git a/plugins/module_utils/network/vyos/vyos.py b/plugins/module_utils/network/vyos/vyos.py index 1d2c508..908395a 100644 --- a/plugins/module_utils/network/vyos/vyos.py +++ b/plugins/module_utils/network/vyos/vyos.py @@ -1,122 +1,124 @@ # This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete work. # # (c) 2016 Red Hat Inc. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # import json from ansible.module_utils._text import to_text from ansible.module_utils.basic import env_fallback from ansible.module_utils.connection import Connection, ConnectionError _DEVICE_CONFIGS = {} vyos_provider_spec = { "host": dict(), "port": dict(type="int"), "username": dict(fallback=(env_fallback, ["ANSIBLE_NET_USERNAME"])), "password": dict( fallback=(env_fallback, ["ANSIBLE_NET_PASSWORD"]), no_log=True ), "ssh_keyfile": dict( fallback=(env_fallback, ["ANSIBLE_NET_SSH_KEYFILE"]), type="path" ), "timeout": dict(type="int"), } vyos_argument_spec = { - "provider": dict(type="dict", options=vyos_provider_spec) + "provider": dict( + type="dict", options=vyos_provider_spec, removed_in_version=2.14 + ), } def get_provider_argspec(): return vyos_provider_spec def get_connection(module): if hasattr(module, "_vyos_connection"): return module._vyos_connection capabilities = get_capabilities(module) network_api = capabilities.get("network_api") if network_api == "cliconf": module._vyos_connection = Connection(module._socket_path) else: module.fail_json(msg="Invalid connection type %s" % network_api) return module._vyos_connection def get_capabilities(module): if hasattr(module, "_vyos_capabilities"): return module._vyos_capabilities try: capabilities = Connection(module._socket_path).get_capabilities() except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) module._vyos_capabilities = json.loads(capabilities) return module._vyos_capabilities def get_config(module, flags=None, format=None): flags = [] if flags is None else flags global _DEVICE_CONFIGS if _DEVICE_CONFIGS != {}: return _DEVICE_CONFIGS else: connection = get_connection(module) try: out = connection.get_config(flags=flags, format=format) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) cfg = to_text(out, errors="surrogate_then_replace").strip() _DEVICE_CONFIGS = cfg return cfg def run_commands(module, commands, check_rc=True): connection = get_connection(module) try: response = connection.run_commands( commands=commands, check_rc=check_rc ) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) return response def load_config(module, commands, commit=False, comment=None): connection = get_connection(module) try: response = connection.edit_config( candidate=commands, commit=commit, comment=comment ) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) return response.get("diff") diff --git a/plugins/modules/_vyos_interface.py b/plugins/modules/_vyos_interface.py deleted file mode 100644 index 71a98c5..0000000 --- a/plugins/modules/_vyos_interface.py +++ /dev/null @@ -1,468 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2017, Ansible by Red Hat, inc -# -# This file is part of Ansible by Red Hat -# -# 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 . -# - -ANSIBLE_METADATA = { - "metadata_version": "1.1", - "status": ["deprecated"], - "supported_by": "network", -} - - -DOCUMENTATION = """ ---- -module: vyos_interface -version_added: "2.4" -author: "Ganesh Nalawade (@ganeshrn)" -short_description: Manage Interface on VyOS network devices -description: - - This module provides declarative management of Interfaces - on VyOS network devices. -deprecated: - removed_in: '2.13' - alternative: vyos_interfaces - why: Updated modules released with more functionality. -notes: - - Tested against VYOS 1.1.7 -options: - name: - description: - - Name of the Interface. - required: true - description: - description: - - Description of Interface. - enabled: - description: - - Interface link status. - type: bool - speed: - description: - - Interface link speed. - mtu: - description: - - Maximum size of transmit packet. - duplex: - description: - - Interface link status. - default: auto - choices: ['full', 'half', 'auto'] - delay: - description: - - Time in seconds to wait before checking for the operational state on remote - device. This wait is applicable for operational state argument which are - I(state) with values C(up)/C(down) and I(neighbors). - default: 10 - neighbors: - description: - - Check the operational state of given interface C(name) for LLDP neighbor. - - The following suboptions are available. - suboptions: - host: - description: - - "LLDP neighbor host for given interface C(name)." - port: - description: - - "LLDP neighbor port to which given interface C(name) is connected." - version_added: 2.5 - aggregate: - description: List of Interfaces definitions. - state: - description: - - State of the Interface configuration, C(up) means present and - operationally up and C(down) means present and operationally C(down) - default: present - choices: ['present', 'absent', 'up', 'down'] -extends_documentation_fragment: vyos -""" - -EXAMPLES = """ -- name: configure interface - vyos_interface: - name: eth0 - description: test-interface - -- name: remove interface - vyos_interface: - name: eth0 - state: absent - -- name: make interface down - vyos_interface: - name: eth0 - enabled: False - -- name: make interface up - vyos_interface: - name: eth0 - enabled: True - -- name: Configure interface speed, mtu, duplex - vyos_interface: - name: eth5 - state: present - speed: 100 - mtu: 256 - duplex: full - -- name: Set interface using aggregate - vyos_interface: - aggregate: - - { name: eth1, description: test-interface-1, speed: 100, duplex: half, mtu: 512} - - { name: eth2, description: test-interface-2, speed: 1000, duplex: full, mtu: 256} - -- name: Disable interface on aggregate - net_interface: - aggregate: - - name: eth1 - - name: eth2 - enabled: False - -- name: Delete interface using aggregate - net_interface: - aggregate: - - name: eth1 - - name: eth2 - state: absent - -- name: Check lldp neighbors intent arguments - vyos_interface: - name: eth0 - neighbors: - - port: eth0 - host: netdev - -- name: Config + intent - vyos_interface: - name: eth1 - enabled: False - state: down -""" - -RETURN = """ -commands: - description: The list of configuration mode commands to send to the device - returned: always, except for the platforms that use Netconf transport to manage the device. - type: list - sample: - - set interfaces ethernet eth0 description "test-interface" - - set interfaces ethernet eth0 speed 100 - - set interfaces ethernet eth0 mtu 256 - - set interfaces ethernet eth0 duplex full -""" -import re - -from copy import deepcopy -from time import sleep - -from ansible.module_utils._text import to_text -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.connection import exec_command -from ansible.module_utils.network.common.utils import ( - conditional, - remove_default_spec, -) -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - load_config, - get_config, -) -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - vyos_argument_spec, -) - - -def search_obj_in_list(name, lst): - for o in lst: - if o["name"] == name: - return o - - return None - - -def map_obj_to_commands(updates): - commands = list() - want, have = updates - - params = ("speed", "description", "duplex", "mtu") - for w in want: - name = w["name"] - disable = w["disable"] - state = w["state"] - - obj_in_have = search_obj_in_list(name, have) - set_interface = "set interfaces ethernet " + name - delete_interface = "delete interfaces ethernet " + name - - if state == "absent" and obj_in_have: - commands.append(delete_interface) - elif state in ("present", "up", "down"): - if obj_in_have: - for item in params: - value = w.get(item) - - if value and value != obj_in_have.get(item): - if item == "description": - value = "'" + str(value) + "'" - commands.append( - set_interface + " " + item + " " + str(value) - ) - - if disable and not obj_in_have.get("disable", False): - commands.append(set_interface + " disable") - elif not disable and obj_in_have.get("disable", False): - commands.append(delete_interface + " disable") - else: - commands.append(set_interface) - for item in params: - value = w.get(item) - if value: - if item == "description": - value = "'" + str(value) + "'" - commands.append( - set_interface + " " + item + " " + str(value) - ) - - if disable: - commands.append(set_interface + " disable") - return commands - - -def map_config_to_obj(module): - data = get_config(module, flags=["| grep interface"]) - obj = [] - for line in data.split("\n"): - if line.startswith("set interfaces ethernet"): - match = re.search(r"set interfaces ethernet (\S+)", line, re.M) - name = match.group(1) - if name: - interface = {} - for item in obj: - if item["name"] == name: - interface = item - break - - if not interface: - interface = {"name": name} - obj.append(interface) - - match = re.search(r"%s (\S+)" % name, line, re.M) - if match: - param = match.group(1) - if param == "description": - match = re.search(r"description (.+)", line, re.M) - description = match.group(1).strip("'") - interface["description"] = description - elif param == "speed": - match = re.search(r"speed (\S+)", line, re.M) - speed = match.group(1).strip("'") - interface["speed"] = speed - elif param == "mtu": - match = re.search(r"mtu (\S+)", line, re.M) - mtu = match.group(1).strip("'") - interface["mtu"] = int(mtu) - elif param == "duplex": - match = re.search(r"duplex (\S+)", line, re.M) - duplex = match.group(1).strip("'") - interface["duplex"] = duplex - elif param.strip("'") == "disable": - interface["disable"] = True - - return obj - - -def map_params_to_obj(module): - obj = [] - aggregate = module.params.get("aggregate") - if aggregate: - for item in aggregate: - for key in item: - if item.get(key) is None: - item[key] = module.params[key] - - d = item.copy() - if d["enabled"]: - d["disable"] = False - else: - d["disable"] = True - - obj.append(d) - else: - params = { - "name": module.params["name"], - "description": module.params["description"], - "speed": module.params["speed"], - "mtu": module.params["mtu"], - "duplex": module.params["duplex"], - "delay": module.params["delay"], - "state": module.params["state"], - "neighbors": module.params["neighbors"], - } - - if module.params["enabled"]: - params.update({"disable": False}) - else: - params.update({"disable": True}) - - obj.append(params) - return obj - - -def check_declarative_intent_params(module, want, result): - failed_conditions = [] - have_neighbors = None - for w in want: - want_state = w.get("state") - want_neighbors = w.get("neighbors") - - if want_state not in ("up", "down") and not want_neighbors: - continue - - if result["changed"]: - sleep(w["delay"]) - - command = "show interfaces ethernet %s" % w["name"] - rc, out, err = exec_command(module, command) - if rc != 0: - module.fail_json( - msg=to_text(err, errors="surrogate_then_replace"), - command=command, - rc=rc, - ) - - if want_state in ("up", "down"): - match = re.search(r"%s (\w+)" % "state", out, re.M) - have_state = None - if match: - have_state = match.group(1) - if have_state is None or not conditional( - want_state, have_state.strip().lower() - ): - failed_conditions.append("state " + "eq(%s)" % want_state) - - if want_neighbors: - have_host = [] - have_port = [] - if have_neighbors is None: - rc, have_neighbors, err = exec_command( - module, "show lldp neighbors detail" - ) - if rc != 0: - module.fail_json( - msg=to_text(err, errors="surrogate_then_replace"), - command=command, - rc=rc, - ) - - if have_neighbors: - lines = have_neighbors.strip().split("Interface: ") - for line in lines: - field = line.split("\n") - if field[0].split(",")[0].strip() == w["name"]: - for item in field: - if item.strip().startswith("SysName:"): - have_host.append(item.split(":")[1].strip()) - if item.strip().startswith("PortDescr:"): - have_port.append(item.split(":")[1].strip()) - for item in want_neighbors: - host = item.get("host") - port = item.get("port") - if host and host not in have_host: - failed_conditions.append("host " + host) - if port and port not in have_port: - failed_conditions.append("port " + port) - - return failed_conditions - - -def main(): - """ main entry point for module execution - """ - neighbors_spec = dict(host=dict(), port=dict()) - - element_spec = dict( - name=dict(), - description=dict(), - speed=dict(), - mtu=dict(type="int"), - duplex=dict(choices=["full", "half", "auto"]), - enabled=dict(default=True, type="bool"), - neighbors=dict(type="list", elements="dict", options=neighbors_spec), - delay=dict(default=10, type="int"), - state=dict( - default="present", choices=["present", "absent", "up", "down"] - ), - ) - - aggregate_spec = deepcopy(element_spec) - aggregate_spec["name"] = dict(required=True) - - # remove default in aggregate spec, to handle common arguments - remove_default_spec(aggregate_spec) - - argument_spec = dict( - aggregate=dict(type="list", elements="dict", options=aggregate_spec) - ) - - argument_spec.update(element_spec) - argument_spec.update(vyos_argument_spec) - - required_one_of = [["name", "aggregate"]] - mutually_exclusive = [["name", "aggregate"]] - - required_together = [["speed", "duplex"]] - module = AnsibleModule( - argument_spec=argument_spec, - required_one_of=required_one_of, - mutually_exclusive=mutually_exclusive, - required_together=required_together, - supports_check_mode=True, - ) - - warnings = list() - - result = {"changed": False} - - if warnings: - result["warnings"] = warnings - - want = map_params_to_obj(module) - have = map_config_to_obj(module) - - commands = map_obj_to_commands((want, have)) - result["commands"] = commands - - if commands: - commit = not module.check_mode - diff = load_config(module, commands, commit=commit) - if diff: - if module._diff: - result["diff"] = {"prepared": diff} - result["changed"] = True - - failed_conditions = check_declarative_intent_params(module, want, result) - - if failed_conditions: - msg = "One or more conditional statements have not been satisfied" - module.fail_json(msg=msg, failed_conditions=failed_conditions) - module.exit_json(**result) - - -if __name__ == "__main__": - main() diff --git a/plugins/modules/_vyos_l3_interface.py b/plugins/modules/_vyos_l3_interface.py deleted file mode 100644 index 054d810..0000000 --- a/plugins/modules/_vyos_l3_interface.py +++ /dev/null @@ -1,328 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2017, Ansible by Red Hat, inc -# -# This file is part of Ansible by Red Hat -# -# 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 . -# - -ANSIBLE_METADATA = { - "metadata_version": "1.1", - "status": ["deprecated"], - "supported_by": "network", -} - - -DOCUMENTATION = """ ---- -module: vyos_l3_interface -version_added: "2.4" -author: "Ricardo Carrillo Cruz (@rcarrillocruz)" -short_description: Manage L3 interfaces on VyOS network devices -description: - - This module provides declarative management of L3 interfaces - on VyOS network devices. -deprecated: - removed_in: '2.13' - alternative: vyos_l3_interfaces - why: Updated modules released with more functionality. -notes: - - Tested against VYOS 1.1.7 -options: - name: - description: - - Name of the L3 interface. - ipv4: - description: - - IPv4 of the L3 interface. - ipv6: - description: - - IPv6 of the L3 interface. - aggregate: - description: List of L3 interfaces definitions - state: - description: - - State of the L3 interface configuration. - default: present - choices: ['present', 'absent'] -extends_documentation_fragment: vyos -""" - -EXAMPLES = """ -- name: Set eth0 IPv4 address - vyos_l3_interface: - name: eth0 - ipv4: 192.168.0.1/24 - -- name: Remove eth0 IPv4 address - vyos_l3_interface: - name: eth0 - state: absent - -- name: Set IP addresses on aggregate - vyos_l3_interface: - aggregate: - - { name: eth1, ipv4: 192.168.2.10/24 } - - { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" } - -- name: Remove IP addresses on aggregate - vyos_l3_interface: - aggregate: - - { name: eth1, ipv4: 192.168.2.10/24 } - - { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" } - state: absent -""" - -RETURN = """ -commands: - description: The list of configuration mode commands to send to the device - returned: always, except for the platforms that use Netconf transport to manage the device. - type: list - sample: - - set interfaces ethernet eth0 address '192.168.0.1/24' -""" - -import socket -import re - -from copy import deepcopy - -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.network.common.utils import ( - is_masklen, - validate_ip_address, -) -from ansible.module_utils.network.common.utils import remove_default_spec -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - load_config, - run_commands, -) -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - vyos_argument_spec, -) - - -def is_ipv4(value): - if value: - address = value.split("/") - if is_masklen(address[1]) and validate_ip_address(address[0]): - return True - return False - - -def is_ipv6(value): - if value: - address = value.split("/") - if 0 <= int(address[1]) <= 128: - try: - socket.inet_pton(socket.AF_INET6, address[0]) - except socket.error: - return False - return True - return False - - -def search_obj_in_list(name, lst): - for o in lst: - if o["name"] == name: - return o - - return None - - -def map_obj_to_commands(updates, module): - commands = list() - want, have = updates - - for w in want: - name = w["name"] - ipv4 = w["ipv4"] - ipv6 = w["ipv6"] - state = w["state"] - - obj_in_have = search_obj_in_list(name, have) - - if state == "absent" and obj_in_have: - if ( - not ipv4 - and not ipv6 - and (obj_in_have["ipv4"] or obj_in_have["ipv6"]) - ): - if name == "lo": - commands.append("delete interfaces loopback lo address") - else: - commands.append( - "delete interfaces ethernet " + name + " address" - ) - else: - if ipv4 and ipv4 in obj_in_have["ipv4"]: - if name == "lo": - commands.append( - "delete interfaces loopback lo address " + ipv4 - ) - else: - commands.append( - "delete interfaces ethernet " - + name - + " address " - + ipv4 - ) - if ipv6 and ipv6 in obj_in_have["ipv6"]: - if name == "lo": - commands.append( - "delete interfaces loopback lo address " + ipv6 - ) - else: - commands.append( - "delete interfaces ethernet " - + name - + " address " - + ipv6 - ) - elif state == "present" and obj_in_have: - if ipv4 and ipv4 not in obj_in_have["ipv4"]: - if name == "lo": - commands.append( - "set interfaces loopback lo address " + ipv4 - ) - else: - commands.append( - "set interfaces ethernet " + name + " address " + ipv4 - ) - - if ipv6 and ipv6 not in obj_in_have["ipv6"]: - if name == "lo": - commands.append( - "set interfaces loopback lo address " + ipv6 - ) - else: - commands.append( - "set interfaces ethernet " + name + " address " + ipv6 - ) - - return commands - - -def map_config_to_obj(module): - obj = [] - output = run_commands(module, ["show interfaces"]) - lines = re.split(r"\n[e|l]", output[0])[1:] - - if len(lines) > 0: - for line in lines: - splitted_line = line.split() - - if len(splitted_line) > 0: - ipv4 = [] - ipv6 = [] - - if splitted_line[0].lower().startswith("th"): - name = "e" + splitted_line[0].lower() - elif splitted_line[0].lower().startswith("o"): - name = "l" + splitted_line[0].lower() - - for i in splitted_line[1:]: - if ("." in i or ":" in i) and "/" in i: - value = i.split(r"\n")[0] - if is_ipv4(value): - ipv4.append(value) - elif is_ipv6(value): - ipv6.append(value) - - obj.append({"name": name, "ipv4": ipv4, "ipv6": ipv6}) - - return obj - - -def map_params_to_obj(module): - obj = [] - - aggregate = module.params.get("aggregate") - if aggregate: - for item in aggregate: - for key in item: - if item.get(key) is None: - item[key] = module.params[key] - - obj.append(item.copy()) - else: - obj.append( - { - "name": module.params["name"], - "ipv4": module.params["ipv4"], - "ipv6": module.params["ipv6"], - "state": module.params["state"], - } - ) - - return obj - - -def main(): - """ main entry point for module execution - """ - element_spec = dict( - name=dict(), - ipv4=dict(), - ipv6=dict(), - state=dict(default="present", choices=["present", "absent"]), - ) - - aggregate_spec = deepcopy(element_spec) - aggregate_spec["name"] = dict(required=True) - - # remove default in aggregate spec, to handle common arguments - remove_default_spec(aggregate_spec) - - argument_spec = dict( - aggregate=dict(type="list", elements="dict", options=aggregate_spec) - ) - - argument_spec.update(element_spec) - argument_spec.update(vyos_argument_spec) - - required_one_of = [["name", "aggregate"]] - mutually_exclusive = [["name", "aggregate"]] - module = AnsibleModule( - argument_spec=argument_spec, - required_one_of=required_one_of, - mutually_exclusive=mutually_exclusive, - supports_check_mode=True, - ) - - warnings = list() - - result = {"changed": False} - - if warnings: - result["warnings"] = warnings - - want = map_params_to_obj(module) - have = map_config_to_obj(module) - - commands = map_obj_to_commands((want, have), module) - result["commands"] = commands - - if commands: - commit = not module.check_mode - load_config(module, commands, commit=commit) - result["changed"] = True - - module.exit_json(**result) - - -if __name__ == "__main__": - main() diff --git a/plugins/modules/_vyos_linkagg.py b/plugins/modules/_vyos_linkagg.py deleted file mode 100644 index 95fbae9..0000000 --- a/plugins/modules/_vyos_linkagg.py +++ /dev/null @@ -1,317 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2017, Ansible by Red Hat, inc -# -# This file is part of Ansible by Red Hat -# -# 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 . -# - -ANSIBLE_METADATA = { - "metadata_version": "1.1", - "status": ["deprecated"], - "supported_by": "network", -} - - -DOCUMENTATION = """ ---- -module: vyos_linkagg -version_added: "2.4" -author: "Ricardo Carrillo Cruz (@rcarrillocruz)" -short_description: Manage link aggregation groups on VyOS network devices -description: - - This module provides declarative management of link aggregation groups - on VyOS network devices. -deprecated: - removed_in: '2.13' - alternative: vyos_lag_interfaces - why: Updated modules released with more functionality. -notes: - - Tested against VYOS 1.1.7 -options: - name: - description: - - Name of the link aggregation group. - required: true - type: str - mode: - description: - - Mode of the link aggregation group. - choices: ['802.3ad', 'active-backup', 'broadcast', - 'round-robin', 'transmit-load-balance', - 'adaptive-load-balance', 'xor-hash', 'on'] - type: str - members: - description: - - List of members of the link aggregation group. - type: list - aggregate: - description: List of link aggregation definitions. - type: list - state: - description: - - State of the link aggregation group. - default: present - choices: ['present', 'absent', 'up', 'down'] - type: str -extends_documentation_fragment: vyos -""" - -EXAMPLES = """ -- name: configure link aggregation group - vyos_linkagg: - name: bond0 - members: - - eth0 - - eth1 - -- name: remove configuration - vyos_linkagg: - name: bond0 - state: absent - -- name: Create aggregate of linkagg definitions - vyos_linkagg: - aggregate: - - { name: bond0, members: [eth1] } - - { name: bond1, members: [eth2] } - -- name: Remove aggregate of linkagg definitions - vyos_linkagg: - aggregate: - - name: bond0 - - name: bond1 - state: absent -""" - -RETURN = """ -commands: - description: The list of configuration mode commands to send to the device - returned: always, except for the platforms that use Netconf transport to manage the device. - type: list - sample: - - set interfaces bonding bond0 - - set interfaces ethernet eth0 bond-group 'bond0' - - set interfaces ethernet eth1 bond-group 'bond0' -""" -from copy import deepcopy - -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.network.common.utils import remove_default_spec -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - load_config, - run_commands, -) -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - vyos_argument_spec, -) - - -def search_obj_in_list(name, lst): - for o in lst: - if o["name"] == name: - return o - - return None - - -def map_obj_to_commands(updates, module): - commands = list() - want, have = updates - - for w in want: - name = w["name"] - members = w.get("members") or [] - mode = w["mode"] - - if mode == "on": - mode = "802.3ad" - - state = w["state"] - - obj_in_have = search_obj_in_list(name, have) - - if state == "absent": - if obj_in_have: - for m in obj_in_have["members"]: - commands.append( - "delete interfaces ethernet " + m + " bond-group" - ) - - commands.append("delete interfaces bonding " + name) - else: - if not obj_in_have: - commands.append( - "set interfaces bonding " + name + " mode " + mode - ) - - for m in members: - commands.append( - "set interfaces ethernet " + m + " bond-group " + name - ) - - if state == "down": - commands.append( - "set interfaces bonding " + name + " disable" - ) - else: - if mode != obj_in_have["mode"]: - commands.append( - "set interfaces bonding " + name + " mode " + mode - ) - - missing_members = list( - set(members) - set(obj_in_have["members"]) - ) - for m in missing_members: - commands.append( - "set interfaces ethernet " + m + " bond-group " + name - ) - - if state == "down" and obj_in_have["state"] == "up": - commands.append( - "set interfaces bonding " + name + " disable" - ) - elif state == "up" and obj_in_have["state"] == "down": - commands.append( - "delete interfaces bonding " + name + " disable" - ) - - return commands - - -def map_config_to_obj(module): - obj = [] - output = run_commands(module, ["show interfaces bonding slaves"]) - lines = output[0].splitlines() - - if len(lines) > 1: - for line in lines[1:]: - splitted_line = line.split() - - name = splitted_line[0] - mode = splitted_line[1] - state = splitted_line[2] - - if len(splitted_line) > 4: - members = splitted_line[4:] - else: - members = [] - - obj.append( - { - "name": name, - "mode": mode, - "members": members, - "state": state, - } - ) - - return obj - - -def map_params_to_obj(module): - obj = [] - aggregate = module.params.get("aggregate") - if aggregate: - for item in aggregate: - for key in item: - if item.get(key) is None: - item[key] = module.params[key] - - obj.append(item.copy()) - else: - obj.append( - { - "name": module.params["name"], - "mode": module.params["mode"], - "members": module.params["members"], - "state": module.params["state"], - } - ) - - return obj - - -def main(): - """ main entry point for module execution - """ - element_spec = dict( - name=dict(), - mode=dict( - choices=[ - "802.3ad", - "active-backup", - "broadcast", - "round-robin", - "transmit-load-balance", - "adaptive-load-balance", - "xor-hash", - "on", - ], - default="802.3ad", - ), - members=dict(type="list"), - state=dict( - default="present", choices=["present", "absent", "up", "down"] - ), - ) - - aggregate_spec = deepcopy(element_spec) - aggregate_spec["name"] = dict(required=True) - - # remove default in aggregate spec, to handle common arguments - remove_default_spec(aggregate_spec) - - argument_spec = dict( - aggregate=dict(type="list", elements="dict", options=aggregate_spec) - ) - - argument_spec.update(element_spec) - argument_spec.update(vyos_argument_spec) - - required_one_of = [["name", "aggregate"]] - mutually_exclusive = [["name", "aggregate"]] - module = AnsibleModule( - argument_spec=argument_spec, - required_one_of=required_one_of, - mutually_exclusive=mutually_exclusive, - supports_check_mode=True, - ) - - warnings = list() - - result = {"changed": False} - - if warnings: - result["warnings"] = warnings - - want = map_params_to_obj(module) - have = map_config_to_obj(module) - - commands = map_obj_to_commands((want, have), module) - result["commands"] = commands - - if commands: - commit = not module.check_mode - load_config(module, commands, commit=commit) - result["changed"] = True - - module.exit_json(**result) - - -if __name__ == "__main__": - main() diff --git a/plugins/modules/_vyos_lldp.py b/plugins/modules/_vyos_lldp.py deleted file mode 100644 index 6978754..0000000 --- a/plugins/modules/_vyos_lldp.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2017, Ansible by Red Hat, inc -# -# This file is part of Ansible by Red Hat -# -# 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 - - -ANSIBLE_METADATA = { - "metadata_version": "1.1", - "status": ["deprecated"], - "supported_by": "network", -} - - -DOCUMENTATION = """ ---- -module: vyos_lldp -version_added: "2.4" -author: "Ricardo Carrillo Cruz (@rcarrillocruz)" -short_description: Manage LLDP configuration on VyOS network devices -description: - - This module provides declarative management of LLDP service - on VyOS network devices. -deprecated: - removed_in: '2.13' - alternative: vyos_lldp_global - why: Updated modules released with more functionality. -notes: - - Tested against VYOS 1.1.7 -options: - interfaces: - description: - - Name of the interfaces. - type: list - state: - description: - - State of the link aggregation group. - default: present - choices: ['present', 'absent', 'enabled', 'disabled'] - type: str -extends_documentation_fragment: vyos -""" - -EXAMPLES = """ -- name: Enable LLDP service - vyos_lldp: - state: present - -- name: Disable LLDP service - vyos_lldp: - state: absent -""" - -RETURN = """ -commands: - description: The list of configuration mode commands to send to the device - returned: always, except for the platforms that use Netconf transport to manage the device. - type: list - sample: - - set service lldp -""" -from ansible.module_utils.basic import AnsibleModule -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - get_config, - load_config, -) -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - vyos_argument_spec, -) - - -def has_lldp(module): - config = get_config(module).splitlines() - - if "set service 'lldp'" in config or "set service lldp" in config: - return True - else: - return False - - -def main(): - """ main entry point for module execution - """ - argument_spec = dict( - interfaces=dict(type="list"), - state=dict( - default="present", - choices=["present", "absent", "enabled", "disabled"], - ), - ) - - argument_spec.update(vyos_argument_spec) - - module = AnsibleModule( - argument_spec=argument_spec, supports_check_mode=True - ) - - warnings = list() - - result = {"changed": False} - - if warnings: - result["warnings"] = warnings - - HAS_LLDP = has_lldp(module) - - commands = [] - - if module.params["state"] == "absent" and HAS_LLDP: - commands.append("delete service lldp") - elif module.params["state"] == "present" and not HAS_LLDP: - commands.append("set service lldp") - - result["commands"] = commands - - if commands: - commit = not module.check_mode - load_config(module, commands, commit=commit) - result["changed"] = True - - module.exit_json(**result) - - -if __name__ == "__main__": - main() diff --git a/plugins/modules/_vyos_lldp_interface.py b/plugins/modules/_vyos_lldp_interface.py deleted file mode 100644 index 6705d57..0000000 --- a/plugins/modules/_vyos_lldp_interface.py +++ /dev/null @@ -1,260 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- - -# (c) 2017, Ansible by Red Hat, inc -# -# This file is part of Ansible by Red Hat -# -# 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 . -# - - -ANSIBLE_METADATA = { - "metadata_version": "1.1", - "status": ["deprecated"], - "supported_by": "network", -} - - -DOCUMENTATION = """ ---- -module: vyos_lldp_interface -version_added: "2.4" -author: "Ricardo Carrillo Cruz (@rcarrillocruz)" -short_description: Manage LLDP interfaces configuration on VyOS network devices -description: - - This module provides declarative management of LLDP interfaces - configuration on VyOS network devices. -deprecated: - removed_in: '2.13' - alternative: vyos_lldp_interfaces - why: Updated modules released with more functionality. -notes: - - Tested against VYOS 1.1.7 -options: - name: - description: - - Name of the interface LLDP should be configured on. - type: str - aggregate: - description: List of interfaces LLDP should be configured on. - type: list - state: - description: - - State of the LLDP configuration. - default: present - choices: ['present', 'absent', 'enabled', 'disabled'] - type: str -extends_documentation_fragment: vyos -""" - -EXAMPLES = """ -- name: Enable LLDP on eth1 - net_lldp_interface: - state: present - -- name: Enable LLDP on specific interfaces - net_lldp_interface: - interfaces: - - eth1 - - eth2 - state: present - -- name: Disable LLDP globally - net_lldp_interface: - state: disabled - -- name: Create aggregate of LLDP interface configurations - vyos_lldp_interface: - aggregate: - - name: eth1 - - name: eth2 - state: present - -- name: Delete aggregate of LLDP interface configurations - vyos_lldp_interface: - aggregate: - - name: eth1 - - name: eth2 - state: absent -""" - -RETURN = """ -commands: - description: The list of configuration mode commands to send to the device - returned: always, except for the platforms that use Netconf transport to manage the device. - type: list - sample: - - set service lldp eth1 - - set service lldp eth2 disable -""" - - -from copy import deepcopy - -from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.network.common.utils import remove_default_spec -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - get_config, - load_config, -) -from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( - vyos_argument_spec, -) - - -def search_obj_in_list(name, lst): - for o in lst: - if o["name"] == name: - return o - - return None - - -def map_obj_to_commands(updates, module): - commands = list() - want, have = updates - - for w in want: - name = w["name"] - state = w["state"] - - obj_in_have = search_obj_in_list(name, have) - - if state == "absent" and obj_in_have: - commands.append("delete service lldp interface " + name) - elif state in ("present", "enabled"): - if not obj_in_have: - commands.append("set service lldp interface " + name) - elif ( - obj_in_have - and obj_in_have["state"] == "disabled" - and state == "enabled" - ): - commands.append( - "delete service lldp interface " + name + " disable" - ) - elif state == "disabled": - if not obj_in_have: - commands.append("set service lldp interface " + name) - commands.append( - "set service lldp interface " + name + " disable" - ) - elif obj_in_have and obj_in_have["state"] != "disabled": - commands.append( - "set service lldp interface " + name + " disable" - ) - - return commands - - -def map_config_to_obj(module): - obj = [] - config = get_config(module).splitlines() - - output = [c for c in config if c.startswith("set service lldp interface")] - - for i in output: - splitted_line = i.split() - - if len(splitted_line) > 5: - new_obj = {"name": splitted_line[4]} - - if splitted_line[5] == "'disable'": - new_obj["state"] = "disabled" - else: - new_obj = {"name": splitted_line[4][1:-1]} - new_obj["state"] = "present" - - obj.append(new_obj) - - return obj - - -def map_params_to_obj(module): - obj = [] - - aggregate = module.params.get("aggregate") - if aggregate: - for item in aggregate: - for key in item: - if item.get(key) is None: - item[key] = module.params[key] - - obj.append(item.copy()) - else: - obj.append( - {"name": module.params["name"], "state": module.params["state"]} - ) - - return obj - - -def main(): - """ main entry point for module execution - """ - element_spec = dict( - name=dict(), - state=dict( - default="present", - choices=["present", "absent", "enabled", "disabled"], - ), - ) - - aggregate_spec = deepcopy(element_spec) - aggregate_spec["name"] = dict(required=True) - - # remove default in aggregate spec, to handle common arguments - remove_default_spec(aggregate_spec) - - argument_spec = dict( - aggregate=dict(type="list", elements="dict", options=aggregate_spec) - ) - - argument_spec.update(element_spec) - argument_spec.update(vyos_argument_spec) - - required_one_of = [["name", "aggregate"]] - mutually_exclusive = [["name", "aggregate"]] - - module = AnsibleModule( - argument_spec=argument_spec, - required_one_of=required_one_of, - mutually_exclusive=mutually_exclusive, - supports_check_mode=True, - ) - - warnings = list() - - result = {"changed": False} - - if warnings: - result["warnings"] = warnings - - want = map_params_to_obj(module) - have = map_config_to_obj(module) - - commands = map_obj_to_commands((want, have), module) - result["commands"] = commands - - if commands: - commit = not module.check_mode - load_config(module, commands, commit=commit) - result["changed"] = True - - module.exit_json(**result) - - -if __name__ == "__main__": - main() diff --git a/plugins/modules/vyos_banner.py b/plugins/modules/vyos_banner.py index 81a985d..b08fb73 100644 --- a/plugins/modules/vyos_banner.py +++ b/plugins/modules/vyos_banner.py @@ -1,197 +1,196 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # 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 . # ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_banner -version_added: "2.4" -author: "Trishna Guha (@trishnaguha)" +DOCUMENTATION = """module: vyos_banner +author: Trishna Guha (@trishnaguha) short_description: Manage multiline banners on VyOS devices description: - - This will configure both pre-login and post-login banners on remote - devices running VyOS. It allows playbooks to add or remote - banner text from the active running configuration. +- This will configure both pre-login and post-login banners on remote devices running + VyOS. It allows playbooks to add or remote banner text from the active running configuration. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). options: banner: description: - - Specifies which banner that should be - configured on the remote device. + - Specifies which banner that should be configured on the remote device. required: true - choices: ['pre-login', 'post-login'] + choices: + - pre-login + - post-login text: description: - - The banner text that should be - present in the remote device running configuration. This argument - accepts a multiline string, with no empty lines. Requires I(state=present). + - The banner text that should be present in the remote device running configuration. + This argument accepts a multiline string, with no empty lines. Requires I(state=present). state: description: - - Specifies whether or not the configuration is present in the current - devices active running configuration. + - Specifies whether or not the configuration is present in the current devices + active running configuration. default: present - choices: ['present', 'absent'] -extends_documentation_fragment: vyos + choices: + - present + - absent +extends_documentation_fragment: +- vyos.vyos.vyos """ EXAMPLES = """ - name: configure the pre-login banner vyos_banner: banner: pre-login text: | this is my pre-login banner that contains a multiline string state: present - name: remove the post-login banner vyos_banner: banner: post-login state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - banner pre-login - this is my pre-login banner - that contains a multiline - string """ import re from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( get_config, load_config, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( vyos_argument_spec, ) def spec_to_commands(updates, module): commands = list() want, have = updates state = module.params["state"] if state == "absent": if have.get("state") != "absent" or ( have.get("state") != "absent" and "text" in have.keys() and have["text"] ): commands.append( "delete system login banner %s" % module.params["banner"] ) elif state == "present": if want["text"] and want["text"].encode().decode( "unicode_escape" ) != have.get("text"): banner_cmd = ( "set system login banner %s " % module.params["banner"] ) banner_cmd += want["text"].strip() commands.append(banner_cmd) return commands def config_to_dict(module): data = get_config(module) output = None obj = {"banner": module.params["banner"], "state": "absent"} for line in data.split("\n"): if line.startswith("set system login banner %s" % obj["banner"]): match = re.findall(r"%s (.*)" % obj["banner"], line, re.M) output = match if output: obj["text"] = output[0].encode().decode("unicode_escape") obj["state"] = "present" return obj def map_params_to_obj(module): text = module.params["text"] if text: text = "%r" % (str(text).strip()) return { "banner": module.params["banner"], "text": text, "state": module.params["state"], } def main(): """ main entry point for module execution """ argument_spec = dict( banner=dict(required=True, choices=["pre-login", "post-login"]), text=dict(), state=dict(default="present", choices=["present", "absent"]), ) argument_spec.update(vyos_argument_spec) required_if = [("state", "present", ("text",))] module = AnsibleModule( argument_spec=argument_spec, required_if=required_if, supports_check_mode=True, ) warnings = list() result = {"changed": False} if warnings: result["warnings"] = warnings want = map_params_to_obj(module) have = config_to_dict(module) commands = spec_to_commands((want, have), module) result["commands"] = commands if commands: commit = not module.check_mode load_config(module, commands, commit=commit) result["changed"] = True module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_command.py b/plugins/modules/vyos_command.py index 6da7352..1853849 100644 --- a/plugins/modules/vyos_command.py +++ b/plugins/modules/vyos_command.py @@ -1,229 +1,223 @@ #!/usr/bin/python # # 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 . # ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_command -version_added: "2.2" -author: "Nathaniel Case (@Qalthos)" +DOCUMENTATION = """module: vyos_command +author: Nathaniel Case (@Qalthos) short_description: Run one or more commands on VyOS devices description: - - The command module allows running one or more commands on remote - devices running VyOS. This module can also be introspected - to validate key parameters before returning successfully. If the - conditional statements are not met in the wait period, the task - fails. - - Certain C(show) commands in VyOS produce many lines of output and - use a custom pager that can cause this module to hang. If the - value of the environment variable C(ANSIBLE_VYOS_TERMINAL_LENGTH) - is not set, the default number of 10000 is used. -extends_documentation_fragment: vyos +- The command module allows running one or more commands on remote devices running + VyOS. This module can also be introspected to validate key parameters before returning + successfully. If the conditional statements are not met in the wait period, the + task fails. +- Certain C(show) commands in VyOS produce many lines of output and use a custom pager + that can cause this module to hang. If the value of the environment variable C(ANSIBLE_VYOS_TERMINAL_LENGTH) + is not set, the default number of 10000 is used. +extends_documentation_fragment: +- vyos.vyos.vyos options: commands: description: - - The ordered set of commands to execute on the remote device - running VyOS. The output from the command execution is - returned to the playbook. If the I(wait_for) argument is - provided, the module is not returned until the condition is - satisfied or the number of retries has been exceeded. + - The ordered set of commands to execute on the remote device running VyOS. The + output from the command execution is returned to the playbook. If the I(wait_for) + argument is provided, the module is not returned until the condition is satisfied + or the number of retries has been exceeded. required: true wait_for: description: - - Specifies what to evaluate from the output of the command - and what conditionals to apply. This argument will cause - the task to wait for a particular conditional to be true - before moving forward. If the conditional is not true - by the configured I(retries), the task fails. See examples. - aliases: ['waitfor'] + - Specifies what to evaluate from the output of the command and what conditionals + to apply. This argument will cause the task to wait for a particular conditional + to be true before moving forward. If the conditional is not true by the configured + I(retries), the task fails. See examples. + aliases: + - waitfor match: description: - - The I(match) argument is used in conjunction with the - I(wait_for) argument to specify the match policy. Valid - values are C(all) or C(any). If the value is set to C(all) - then all conditionals in the wait_for must be satisfied. If - the value is set to C(any) then only one of the values must be - satisfied. + - The I(match) argument is used in conjunction with the I(wait_for) argument to + specify the match policy. Valid values are C(all) or C(any). If the value is + set to C(all) then all conditionals in the wait_for must be satisfied. If the + value is set to C(any) then only one of the values must be satisfied. default: all - choices: ['any', 'all'] + choices: + - any + - all retries: description: - - Specifies the number of retries a command should be tried - before it is considered failed. The command is run on the - target device every retry and evaluated against the I(wait_for) - conditionals. + - Specifies the number of retries a command should be tried before it is considered + failed. The command is run on the target device every retry and evaluated against + the I(wait_for) conditionals. default: 10 interval: description: - - Configures the interval in seconds to wait between I(retries) - of the command. If the command does not pass the specified - conditions, the interval indicates how long to wait before - trying the command again. + - Configures the interval in seconds to wait between I(retries) of the command. + If the command does not pass the specified conditions, the interval indicates + how long to wait before trying the command again. default: 1 - notes: - - Tested against VyOS 1.1.8 (helium). - - Running C(show system boot-messages all) will cause the module to hang since - VyOS is using a custom pager setting to display the output of that command. - - If a command sent to the device requires answering a prompt, it is possible - to pass a dict containing I(command), I(answer) and I(prompt). See examples. - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- Running C(show system boot-messages all) will cause the module to hang since VyOS + is using a custom pager setting to display the output of that command. +- If a command sent to the device requires answering a prompt, it is possible to pass + a dict containing I(command), I(answer) and I(prompt). See examples. +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). """ EXAMPLES = """ tasks: - name: show configuration on ethernet devices eth0 and eth1 vyos_command: commands: - show interfaces ethernet {{ item }} with_items: - eth0 - eth1 - name: run multiple commands and check if version output contains specific version string vyos_command: commands: - show version - show hardware cpu wait_for: - "result[0] contains 'VyOS 1.1.7'" - name: run command that requires answering a prompt vyos_command: commands: - command: 'rollback 1' prompt: 'Proceed with reboot? [confirm][y]' answer: y """ RETURN = """ stdout: description: The set of responses from the commands returned: always apart from low level errors (such as action plugin) type: list sample: ['...', '...'] stdout_lines: description: The value of stdout split into a list returned: always type: list sample: [['...', '...'], ['...'], ['...']] failed_conditions: description: The list of conditionals that have failed returned: failed type: list sample: ['...', '...'] warnings: description: The list of warnings (if any) generated by module based on arguments returned: always type: list sample: ['...', '...'] """ import time from ansible.module_utils._text import to_text from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.network.common.parsing import Conditional -from ansible.module_utils.network.common.utils import ( +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.parsing import ( + Conditional, +) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( transform_commands, to_lines, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( run_commands, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( vyos_argument_spec, ) def parse_commands(module, warnings): commands = transform_commands(module) if module.check_mode: for item in list(commands): if not item["command"].startswith("show"): warnings.append( "Only show commands are supported when using check mode, not " "executing %s" % item["command"] ) commands.remove(item) return commands def main(): spec = dict( commands=dict(type="list", required=True), wait_for=dict(type="list", aliases=["waitfor"]), match=dict(default="all", choices=["all", "any"]), retries=dict(default=10, type="int"), interval=dict(default=1, type="int"), ) spec.update(vyos_argument_spec) module = AnsibleModule(argument_spec=spec, supports_check_mode=True) warnings = list() result = {"changed": False, "warnings": warnings} commands = parse_commands(module, warnings) wait_for = module.params["wait_for"] or list() try: conditionals = [Conditional(c) for c in wait_for] except AttributeError as exc: module.fail_json(msg=to_text(exc)) retries = module.params["retries"] interval = module.params["interval"] match = module.params["match"] for _ in range(retries): responses = run_commands(module, commands) for item in list(conditionals): if item(responses): if match == "any": conditionals = list() break conditionals.remove(item) if not conditionals: break time.sleep(interval) if conditionals: failed_conditions = [item.raw for item in conditionals] msg = "One or more conditional statements have not been satisfied" module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update( - {"stdout": responses, "stdout_lines": list(to_lines(responses))} + {"stdout": responses, "stdout_lines": list(to_lines(responses)),} ) module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_config.py b/plugins/modules/vyos_config.py index 7c9f3ab..24fa161 100644 --- a/plugins/modules/vyos_config.py +++ b/plugins/modules/vyos_config.py @@ -1,351 +1,354 @@ #!/usr/bin/python # # 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 . # ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_config -version_added: "2.2" -author: "Nathaniel Case (@Qalthos)" +DOCUMENTATION = """module: vyos_config +author: Nathaniel Case (@Qalthos) short_description: Manage VyOS configuration on remote device description: - - This module provides configuration file management of VyOS - devices. It provides arguments for managing both the - configuration file and state of the active configuration. All - configuration statements are based on `set` and `delete` commands - in the device configuration. -extends_documentation_fragment: vyos +- This module provides configuration file management of VyOS devices. It provides + arguments for managing both the configuration file and state of the active configuration. + All configuration statements are based on `set` and `delete` commands in the device + configuration. +extends_documentation_fragment: +- vyos.vyos.vyos notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). options: lines: description: - - The ordered set of configuration lines to be managed and - compared with the existing configuration on the remote - device. + - The ordered set of configuration lines to be managed and compared with the existing + configuration on the remote device. src: description: - - The C(src) argument specifies the path to the source config - file to load. The source config file can either be in - bracket format or set format. The source file can include - Jinja2 template variables. + - The C(src) argument specifies the path to the source config file to load. The + source config file can either be in bracket format or set format. The source + file can include Jinja2 template variables. match: description: - - The C(match) argument controls the method used to match - against the current active configuration. By default, the - desired config is matched against the active config and the - deltas are loaded. If the C(match) argument is set to C(none) - the active configuration is ignored and the configuration is - always loaded. + - The C(match) argument controls the method used to match against the current + active configuration. By default, the desired config is matched against the + active config and the deltas are loaded. If the C(match) argument is set to + C(none) the active configuration is ignored and the configuration is always + loaded. default: line - choices: ['line', 'none'] + choices: + - line + - none backup: description: - - The C(backup) argument will backup the current devices active - configuration to the Ansible control host prior to making any - changes. If the C(backup_options) value is not given, the - backup file will be located in the backup folder in the playbook - root directory or role root directory, if playbook is part of an - ansible role. If the directory does not exist, it is created. + - The C(backup) argument will backup the current devices active configuration + to the Ansible control host prior to making any changes. If the C(backup_options) + value is not given, the backup file will be located in the backup folder in + the playbook root directory or role root directory, if playbook is part of an + ansible role. If the directory does not exist, it is created. type: bool default: 'no' comment: description: - - Allows a commit description to be specified to be included - when the configuration is committed. If the configuration is - not changed or committed, this argument is ignored. - default: 'configured by vyos_config' + - Allows a commit description to be specified to be included when the configuration + is committed. If the configuration is not changed or committed, this argument + is ignored. + default: configured by vyos_config config: description: - - The C(config) argument specifies the base configuration to use - to compare against the desired configuration. If this value - is not specified, the module will automatically retrieve the - current active configuration from the remote device. + - The C(config) argument specifies the base configuration to use to compare against + the desired configuration. If this value is not specified, the module will + automatically retrieve the current active configuration from the remote device. save: description: - - The C(save) argument controls whether or not changes made - to the active configuration are saved to disk. This is - independent of committing the config. When set to True, the - active configuration is saved. + - The C(save) argument controls whether or not changes made to the active configuration + are saved to disk. This is independent of committing the config. When set + to True, the active configuration is saved. type: bool default: 'no' backup_options: description: - - This is a dict object containing configurable options related to backup file path. - The value of this option is read only when C(backup) is set to I(yes), if C(backup) is set - to I(no) this option will be silently ignored. + - This is a dict object containing configurable options related to backup file + path. The value of this option is read only when C(backup) is set to I(yes), + if C(backup) is set to I(no) this option will be silently ignored. suboptions: filename: description: - - The filename to be used to store the backup configuration. If the the filename - is not given it will be generated based on the hostname, current time and date - in format defined by _config.@ + - The filename to be used to store the backup configuration. If the the filename + is not given it will be generated based on the hostname, current time and + date in format defined by _config.@ dir_path: description: - - This option provides the path ending with directory name in which the backup - configuration file will be stored. If the directory does not exist it will be first - created and the filename is either the value of C(filename) or default filename - as described in C(filename) options description. If the path value is not given - in that case a I(backup) directory will be created in the current working directory - and backup configuration will be copied in C(filename) within I(backup) directory. + - This option provides the path ending with directory name in which the backup + configuration file will be stored. If the directory does not exist it will + be first created and the filename is either the value of C(filename) or + default filename as described in C(filename) options description. If the + path value is not given in that case a I(backup) directory will be created + in the current working directory and backup configuration will be copied + in C(filename) within I(backup) directory. type: path type: dict - version_added: "2.8" """ EXAMPLES = """ - name: configure the remote device vyos_config: lines: - set system host-name {{ inventory_hostname }} - set service lldp - delete service dhcp-server - name: backup and load from file vyos_config: src: vyos.cfg backup: yes - name: render a Jinja2 template onto the VyOS router vyos_config: src: vyos_template.j2 - name: for idempotency, use full-form commands vyos_config: lines: # - set int eth eth2 description 'OUTSIDE' - set interface ethernet eth2 description 'OUTSIDE' - name: configurable backup path vyos_config: backup: yes backup_options: filename: backup.cfg dir_path: /home/user """ RETURN = """ commands: description: The list of configuration commands sent to the device returned: always type: list sample: ['...', '...'] filtered: description: The list of configuration commands removed to avoid a load failure returned: always type: list sample: ['...', '...'] backup_path: description: The full path to the backup file returned: when backup is yes type: str sample: /playbooks/ansible/backup/vyos_config.2016-07-16@22:28:34 filename: description: The name of the backup file returned: when backup is yes and filename is not specified in backup options type: str sample: vyos_config.2016-07-16@22:28:34 shortname: description: The full path to the backup file excluding the timestamp returned: when backup is yes and filename is not specified in backup options type: str sample: /playbooks/ansible/backup/vyos_config date: description: The date extracted from the backup file name returned: when backup is yes type: str sample: "2016-07-16" time: description: The time extracted from the backup file name returned: when backup is yes type: str sample: "22:28:34" """ import re from ansible.module_utils._text import to_text from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import ConnectionError from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( load_config, get_config, run_commands, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( vyos_argument_spec, get_connection, ) DEFAULT_COMMENT = "configured by vyos_config" CONFIG_FILTERS = [ re.compile(r"set system login user \S+ authentication encrypted-password") ] def get_candidate(module): contents = module.params["src"] or module.params["lines"] if module.params["src"]: contents = format_commands(contents.splitlines()) contents = "\n".join(contents) return contents def format_commands(commands): - return [line for line in commands if len(line.strip()) > 0] + """ + This function format the input commands and removes the prepend white spaces + for command lines having 'set' or 'delete' and it skips empty lines. + :param commands: + :return: list of commands + """ + return [ + line.strip() if line.split()[0] in ("set", "delete") else line + for line in commands + if len(line.strip()) > 0 + ] def diff_config(commands, config): config = [str(c).replace("'", "") for c in config.splitlines()] updates = list() visited = set() for line in commands: item = str(line).replace("'", "") if not item.startswith("set") and not item.startswith("delete"): raise ValueError("line must start with either `set` or `delete`") elif item.startswith("set") and item not in config: updates.append(line) elif item.startswith("delete"): if not config: updates.append(line) else: item = re.sub(r"delete", "set", item) for entry in config: if entry.startswith(item) and line not in visited: updates.append(line) visited.add(line) return list(updates) def sanitize_config(config, result): result["filtered"] = list() index_to_filter = list() for regex in CONFIG_FILTERS: for index, line in enumerate(list(config)): if regex.search(line): result["filtered"].append(line) index_to_filter.append(index) # Delete all filtered configs for filter_index in sorted(index_to_filter, reverse=True): del config[filter_index] def run(module, result): # get the current active config from the node or passed in via # the config param config = module.params["config"] or get_config(module) # create the candidate config object from the arguments candidate = get_candidate(module) # create loadable config that includes only the configuration updates connection = get_connection(module) try: response = connection.get_diff( candidate=candidate, running=config, diff_match=module.params["match"], ) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) commands = response.get("config_diff") sanitize_config(commands, result) result["commands"] = commands commit = not module.check_mode comment = module.params["comment"] diff = None if commands: diff = load_config(module, commands, commit=commit, comment=comment) if result.get("filtered"): result["warnings"].append( "Some configuration commands were " "removed, please see the filtered key" ) result["changed"] = True if module._diff: result["diff"] = {"prepared": diff} def main(): backup_spec = dict(filename=dict(), dir_path=dict(type="path")) argument_spec = dict( src=dict(type="path"), lines=dict(type="list"), match=dict(default="line", choices=["line", "none"]), comment=dict(default=DEFAULT_COMMENT), config=dict(), backup=dict(type="bool", default=False), backup_options=dict(type="dict", options=backup_spec), save=dict(type="bool", default=False), ) argument_spec.update(vyos_argument_spec) mutually_exclusive = [("lines", "src")] module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True, ) warnings = list() result = dict(changed=False, warnings=warnings) if module.params["backup"]: result["__backup__"] = get_config(module=module) if any((module.params["src"], module.params["lines"])): run(module, result) if module.params["save"]: diff = run_commands(module, commands=["configure", "compare saved"])[1] if diff != "[edit]": run_commands(module, commands=["save"]) result["changed"] = True run_commands(module, commands=["exit"]) module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_facts.py b/plugins/modules/vyos_facts.py index 125b256..9eaa278 100644 --- a/plugins/modules/vyos_facts.py +++ b/plugins/modules/vyos_facts.py @@ -1,182 +1,174 @@ #!/usr/bin/python # -*- 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 module file for vyos_facts """ ANSIBLE_METADATA = { "metadata_version": "1.1", "status": [u"preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_facts -version_added: 2.2 +DOCUMENTATION = """module: vyos_facts short_description: Get facts about vyos devices. description: - - Collects facts from network devices running the vyos operating - system. This module places the facts gathered in the fact tree keyed by the - respective resource name. The facts module will always collect a - base set of facts from the device and can enable or disable - collection of additional facts. +- Collects facts from network devices running the vyos operating system. This module + places the facts gathered in the fact tree keyed by the respective resource name. The + facts module will always collect a base set of facts from the device and can enable + or disable collection of additional facts. author: - - Nathaniel Case (@qalthos) - - Nilashish Chakraborty (@Nilashishc) - - Rohit Thakur (@rohitthakur2590) -extends_documentation_fragment: vyos +- Nathaniel Case (@qalthos) +- Nilashish Chakraborty (@Nilashishc) +- Rohit Thakur (@rohitthakur2590) +extends_documentation_fragment: +- vyos.vyos.vyos notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). options: gather_subset: description: - - When supplied, this argument will restrict the facts collected - to a given subset. Possible values for this argument include - all, default, config, and neighbors. Can specify a list of - values to include a larger subset. Values can also be used - with an initial C(M(!)) to specify that a specific subset should - not be collected. + - When supplied, this argument will restrict the facts collected to a given subset. Possible + values for this argument include all, default, config, and neighbors. Can specify + a list of values to include a larger subset. Values can also be used with an + initial C(M(!)) to specify that a specific subset should not be collected. required: false - default: "!config" + default: '!config' gather_network_resources: description: - - When supplied, this argument will restrict the facts collected - to a given subset. Possible values for this argument include - all and the resources like interfaces. - Can specify a list of values to include a larger subset. Values - can also be used with an initial C(M(!)) to specify that a - specific subset should not be collected. - Valid subsets are 'all', 'interfaces', 'l3_interfaces', 'lag_interfaces', - 'lldp_global', 'lldp_interfaces'. + - When supplied, this argument will restrict the facts collected to a given subset. + Possible values for this argument include all and the resources like interfaces. + Can specify a list of values to include a larger subset. Values can also be + used with an initial C(M(!)) to specify that a specific subset should not be + collected. Valid subsets are 'all', 'interfaces', 'l3_interfaces', 'lag_interfaces', + 'lldp_global', 'lldp_interfaces'. required: false - version_added: "2.9" """ EXAMPLES = """ # Gather all facts - vyos_facts: gather_subset: all gather_network_resources: all # collect only the config and default facts - vyos_facts: gather_subset: config # collect everything exception the config - vyos_facts: gather_subset: "!config" # Collect only the interfaces facts - vyos_facts: gather_subset: - '!all' - '!min' gather_network_resources: - interfaces # Do not collect interfaces facts - vyos_facts: gather_network_resources: - "!interfaces" # Collect interfaces and minimal default facts - vyos_facts: gather_subset: min gather_network_resources: interfaces """ RETURN = """ ansible_net_config: description: The running-config from the device returned: when config is configured type: str ansible_net_commits: description: The set of available configuration revisions returned: when present type: list ansible_net_hostname: description: The configured system hostname returned: always type: str ansible_net_model: description: The device model string returned: always type: str ansible_net_serialnum: description: The serial number of the device returned: always type: str ansible_net_version: description: The version of the software running returned: always type: str ansible_net_neighbors: description: The set of LLDP neighbors returned: when interface is configured type: list ansible_net_gather_subset: description: The list of subsets gathered by the module returned: always type: list ansible_net_api: description: The name of the transport returned: always type: str ansible_net_python_version: description: The Python version Ansible controller is using returned: always type: str ansible_net_gather_network_resources: description: The list of fact resource subsets collected from the device returned: always type: list """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.facts.facts import ( FactsArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.facts.facts import ( Facts, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( vyos_argument_spec, ) def main(): """ Main entry point for module execution :returns: ansible_facts """ argument_spec = FactsArgs.argument_spec - argument_spec.update(vyos_argument_spec) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) - warnings = [ - "default value for `gather_subset` " - "will be changed to `min` from `!config` v2.11 onwards" - ] + warnings = [] + if module.params["gather_subset"] == "!config": + warnings.append( + "default value for `gather_subset` will be changed to `min` from `!config` v2.11 onwards" + ) result = Facts(module).get_facts() ansible_facts, additional_warnings = result warnings.extend(additional_warnings) module.exit_json(ansible_facts=ansible_facts, warnings=warnings) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_interface.py b/plugins/modules/vyos_interface.py deleted file mode 120000 index 3459fa1..0000000 --- a/plugins/modules/vyos_interface.py +++ /dev/null @@ -1 +0,0 @@ -_vyos_interface.py \ No newline at end of file diff --git a/plugins/modules/vyos_interface.py b/plugins/modules/vyos_interface.py new file mode 100644 index 0000000..175cf3b --- /dev/null +++ b/plugins/modules/vyos_interface.py @@ -0,0 +1,471 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2017, Ansible by Red Hat, inc +# +# This file is part of Ansible by Red Hat +# +# 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 . +# + +ANSIBLE_METADATA = { + "metadata_version": "1.1", + "status": ["deprecated"], + "supported_by": "network", +} + + +DOCUMENTATION = """module: vyos_interface +author: Ganesh Nalawade (@ganeshrn) +short_description: Manage Interface on VyOS network devices +description: +- This module provides declarative management of Interfaces on VyOS network devices. +deprecated: + removed_in: '2.13' + alternative: vyos_interfaces + why: Updated modules released with more functionality. +notes: +- Tested against VYOS 1.1.7 +options: + name: + description: + - Name of the Interface. + required: true + description: + description: + - Description of Interface. + enabled: + description: + - Interface link status. + type: bool + speed: + description: + - Interface link speed. + mtu: + description: + - Maximum size of transmit packet. + duplex: + description: + - Interface link status. + default: auto + choices: + - full + - half + - auto + delay: + description: + - Time in seconds to wait before checking for the operational state on remote + device. This wait is applicable for operational state argument which are I(state) + with values C(up)/C(down) and I(neighbors). + default: 10 + neighbors: + description: + - Check the operational state of given interface C(name) for LLDP neighbor. + - The following suboptions are available. + suboptions: + host: + description: + - LLDP neighbor host for given interface C(name). + port: + description: + - LLDP neighbor port to which given interface C(name) is connected. + aggregate: + description: List of Interfaces definitions. + state: + description: + - State of the Interface configuration, C(up) means present and operationally + up and C(down) means present and operationally C(down) + default: present + choices: + - present + - absent + - up + - down +extends_documentation_fragment: +- vyos.vyos.vyos +""" + +EXAMPLES = """ +- name: configure interface + vyos_interface: + name: eth0 + description: test-interface + +- name: remove interface + vyos_interface: + name: eth0 + state: absent + +- name: make interface down + vyos_interface: + name: eth0 + enabled: False + +- name: make interface up + vyos_interface: + name: eth0 + enabled: True + +- name: Configure interface speed, mtu, duplex + vyos_interface: + name: eth5 + state: present + speed: 100 + mtu: 256 + duplex: full + +- name: Set interface using aggregate + vyos_interface: + aggregate: + - { name: eth1, description: test-interface-1, speed: 100, duplex: half, mtu: 512} + - { name: eth2, description: test-interface-2, speed: 1000, duplex: full, mtu: 256} + +- name: Disable interface on aggregate + net_interface: + aggregate: + - name: eth1 + - name: eth2 + enabled: False + +- name: Delete interface using aggregate + net_interface: + aggregate: + - name: eth1 + - name: eth2 + state: absent + +- name: Check lldp neighbors intent arguments + vyos_interface: + name: eth0 + neighbors: + - port: eth0 + host: netdev + +- name: Config + intent + vyos_interface: + name: eth1 + enabled: False + state: down +""" + +RETURN = """ +commands: + description: The list of configuration mode commands to send to the device + returned: always, except for the platforms that use Netconf transport to manage the device. + type: list + sample: + - set interfaces ethernet eth0 description "test-interface" + - set interfaces ethernet eth0 speed 100 + - set interfaces ethernet eth0 mtu 256 + - set interfaces ethernet eth0 duplex full +""" +import re + +from copy import deepcopy +from time import sleep + +from ansible.module_utils._text import to_text +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.connection import exec_command +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + conditional, + remove_default_spec, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + load_config, + get_config, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + vyos_argument_spec, +) + + +def search_obj_in_list(name, lst): + for o in lst: + if o["name"] == name: + return o + + return None + + +def map_obj_to_commands(updates): + commands = list() + want, have = updates + + params = ("speed", "description", "duplex", "mtu") + for w in want: + name = w["name"] + disable = w["disable"] + state = w["state"] + + obj_in_have = search_obj_in_list(name, have) + set_interface = "set interfaces ethernet " + name + delete_interface = "delete interfaces ethernet " + name + + if state == "absent" and obj_in_have: + commands.append(delete_interface) + elif state in ("present", "up", "down"): + if obj_in_have: + for item in params: + value = w.get(item) + + if value and value != obj_in_have.get(item): + if item == "description": + value = "'" + str(value) + "'" + commands.append( + set_interface + " " + item + " " + str(value) + ) + + if disable and not obj_in_have.get("disable", False): + commands.append(set_interface + " disable") + elif not disable and obj_in_have.get("disable", False): + commands.append(delete_interface + " disable") + else: + commands.append(set_interface) + for item in params: + value = w.get(item) + if value: + if item == "description": + value = "'" + str(value) + "'" + commands.append( + set_interface + " " + item + " " + str(value) + ) + + if disable: + commands.append(set_interface + " disable") + return commands + + +def map_config_to_obj(module): + data = get_config(module, flags=["| grep interface"]) + obj = [] + for line in data.split("\n"): + if line.startswith("set interfaces ethernet"): + match = re.search(r"set interfaces ethernet (\S+)", line, re.M) + name = match.group(1) + if name: + interface = {} + for item in obj: + if item["name"] == name: + interface = item + break + + if not interface: + interface = {"name": name} + obj.append(interface) + + match = re.search(r"%s (\S+)" % name, line, re.M) + if match: + param = match.group(1) + if param == "description": + match = re.search(r"description (.+)", line, re.M) + description = match.group(1).strip("'") + interface["description"] = description + elif param == "speed": + match = re.search(r"speed (\S+)", line, re.M) + speed = match.group(1).strip("'") + interface["speed"] = speed + elif param == "mtu": + match = re.search(r"mtu (\S+)", line, re.M) + mtu = match.group(1).strip("'") + interface["mtu"] = int(mtu) + elif param == "duplex": + match = re.search(r"duplex (\S+)", line, re.M) + duplex = match.group(1).strip("'") + interface["duplex"] = duplex + elif param.strip("'") == "disable": + interface["disable"] = True + + return obj + + +def map_params_to_obj(module): + obj = [] + aggregate = module.params.get("aggregate") + if aggregate: + for item in aggregate: + for key in item: + if item.get(key) is None: + item[key] = module.params[key] + + d = item.copy() + if d["enabled"]: + d["disable"] = False + else: + d["disable"] = True + + obj.append(d) + else: + params = { + "name": module.params["name"], + "description": module.params["description"], + "speed": module.params["speed"], + "mtu": module.params["mtu"], + "duplex": module.params["duplex"], + "delay": module.params["delay"], + "state": module.params["state"], + "neighbors": module.params["neighbors"], + } + + if module.params["enabled"]: + params.update({"disable": False}) + else: + params.update({"disable": True}) + + obj.append(params) + return obj + + +def check_declarative_intent_params(module, want, result): + failed_conditions = [] + have_neighbors = None + for w in want: + want_state = w.get("state") + want_neighbors = w.get("neighbors") + + if want_state not in ("up", "down") and not want_neighbors: + continue + + if result["changed"]: + sleep(w["delay"]) + + command = "show interfaces ethernet %s" % w["name"] + rc, out, err = exec_command(module, command) + if rc != 0: + module.fail_json( + msg=to_text(err, errors="surrogate_then_replace"), + command=command, + rc=rc, + ) + + if want_state in ("up", "down"): + match = re.search(r"%s (\w+)" % "state", out, re.M) + have_state = None + if match: + have_state = match.group(1) + if have_state is None or not conditional( + want_state, have_state.strip().lower() + ): + failed_conditions.append("state " + "eq(%s)" % want_state) + + if want_neighbors: + have_host = [] + have_port = [] + if have_neighbors is None: + rc, have_neighbors, err = exec_command( + module, "show lldp neighbors detail" + ) + if rc != 0: + module.fail_json( + msg=to_text(err, errors="surrogate_then_replace"), + command=command, + rc=rc, + ) + + if have_neighbors: + lines = have_neighbors.strip().split("Interface: ") + for line in lines: + field = line.split("\n") + if field[0].split(",")[0].strip() == w["name"]: + for item in field: + if item.strip().startswith("SysName:"): + have_host.append(item.split(":")[1].strip()) + if item.strip().startswith("PortDescr:"): + have_port.append(item.split(":")[1].strip()) + for item in want_neighbors: + host = item.get("host") + port = item.get("port") + if host and host not in have_host: + failed_conditions.append("host " + host) + if port and port not in have_port: + failed_conditions.append("port " + port) + + return failed_conditions + + +def main(): + """ main entry point for module execution + """ + neighbors_spec = dict(host=dict(), port=dict()) + + element_spec = dict( + name=dict(), + description=dict(), + speed=dict(), + mtu=dict(type="int"), + duplex=dict(choices=["full", "half", "auto"]), + enabled=dict(default=True, type="bool"), + neighbors=dict(type="list", elements="dict", options=neighbors_spec), + delay=dict(default=10, type="int"), + state=dict( + default="present", choices=["present", "absent", "up", "down"] + ), + ) + + aggregate_spec = deepcopy(element_spec) + aggregate_spec["name"] = dict(required=True) + + # remove default in aggregate spec, to handle common arguments + remove_default_spec(aggregate_spec) + + argument_spec = dict( + aggregate=dict(type="list", elements="dict", options=aggregate_spec), + ) + + argument_spec.update(element_spec) + argument_spec.update(vyos_argument_spec) + + required_one_of = [["name", "aggregate"]] + mutually_exclusive = [["name", "aggregate"]] + + required_together = [["speed", "duplex"]] + module = AnsibleModule( + argument_spec=argument_spec, + required_one_of=required_one_of, + mutually_exclusive=mutually_exclusive, + required_together=required_together, + supports_check_mode=True, + ) + + warnings = list() + + result = {"changed": False} + + if warnings: + result["warnings"] = warnings + + want = map_params_to_obj(module) + have = map_config_to_obj(module) + + commands = map_obj_to_commands((want, have)) + result["commands"] = commands + + if commands: + commit = not module.check_mode + diff = load_config(module, commands, commit=commit) + if diff: + if module._diff: + result["diff"] = {"prepared": diff} + result["changed"] = True + + failed_conditions = check_declarative_intent_params(module, want, result) + + if failed_conditions: + msg = "One or more conditional statements have not been satisfied" + module.fail_json(msg=msg, failed_conditions=failed_conditions) + module.exit_json(**result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/vyos_interfaces.py b/plugins/modules/vyos_interfaces.py index 096fd1f..93df4e4 100644 --- a/plugins/modules/vyos_interfaces.py +++ b/plugins/modules/vyos_interfaces.py @@ -1,885 +1,891 @@ #!/usr/bin/python # -*- 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) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The module file for vyos_interfaces """ from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_interfaces -version_added: 2.9 +DOCUMENTATION = """module: vyos_interfaces short_description: Manages interface attributes of VyOS network devices. description: - - This module manages the interface attributes on VyOS network devices. - - This module supports managing base attributes of Ethernet, Bonding, - VXLAN, Loopback and Virtual Tunnel Interfaces. +- This module manages the interface attributes on VyOS network devices. +- This module supports managing base attributes of Ethernet, Bonding, VXLAN, Loopback + and Virtual Tunnel Interfaces. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). author: Nilashish Chakraborty (@nilashishc) options: config: description: The provided interfaces configuration. type: list suboptions: name: description: - Full name of the interface, e.g. eth0, eth1, bond0, vti1, vxlan2. type: str - required: True + required: true description: description: - - Interface description. + - Interface description. type: str duplex: description: - - Interface duplex mode. - - Applicable for Ethernet interfaces only. - choices: ['full', 'half', 'auto'] + - Interface duplex mode. + - Applicable for Ethernet interfaces only. + choices: + - full + - half + - auto type: str enabled: - default: True + default: true description: - - Administrative state of the interface. - - Set the value to C(true) to administratively enable - the interface or C(false) to disable it. + - Administrative state of the interface. + - Set the value to C(true) to administratively enable the interface or C(false) + to disable it. type: bool mtu: description: - - MTU for a specific interface. Refer to vendor documentation for valid values. - - Applicable for Ethernet, Bonding, VXLAN and Virtual Tunnel interfaces. + - MTU for a specific interface. Refer to vendor documentation for valid values. + - Applicable for Ethernet, Bonding, VXLAN and Virtual Tunnel interfaces. type: int speed: description: - - Interface link speed. - - Applicable for Ethernet interfaces only. + - Interface link speed. + - Applicable for Ethernet interfaces only. type: str - choices: ['auto', '10', '100', '1000', '2500', '10000'] + choices: + - auto + - '10' + - '100' + - '1000' + - '2500' + - '10000' vifs: description: - - Virtual sub-interfaces related configuration. - - 802.1Q VLAN interfaces are represented as virtual sub-interfaces in VyOS. + - Virtual sub-interfaces related configuration. + - 802.1Q VLAN interfaces are represented as virtual sub-interfaces in VyOS. type: list suboptions: vlan_id: description: - - Identifier for the virtual sub-interface. + - Identifier for the virtual sub-interface. type: int description: description: - - Virtual sub-interface description. + - Virtual sub-interface description. type: str enabled: description: - - Administrative state of the virtual sub-interface. - - Set the value to C(true) to administratively enable - the interface or C(false) to disable it. + - Administrative state of the virtual sub-interface. + - Set the value to C(true) to administratively enable the interface or + C(false) to disable it. type: bool - default: True + default: true mtu: description: - - MTU for the virtual sub-interface. - - Refer to vendor documentation for valid values. + - MTU for the virtual sub-interface. + - Refer to vendor documentation for valid values. type: int state: description: - - The state of the configuration after module completion. + - The state of the configuration after module completion. type: str choices: - merged - replaced - overridden - deleted default: merged """ EXAMPLES = """ # Using merged # # ------------- # Before state: # ------------- # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces loopback lo - name: Merge provided configuration with device configuration vyos_interfaces: config: - name: eth2 description: 'Configured by Ansible' enabled: True vifs: - vlan_id: 200 description: "VIF 200 - ETH2" - name: eth3 description: 'Configured by Ansible' mtu: 1500 - name: bond1 description: 'Bond - 1' mtu: 1200 - name: vti2 description: 'VTI - 2' enabled: false state: merged # # # ------------------------- # Module Execution Result # ------------------------- # # "before": [ # { # "enabled": true, # "name": "lo" # }, # { # "enabled": true, # "name": "eth3" # }, # { # "enabled": true, # "name": "eth2" # }, # { # "enabled": true, # "name": "eth1" # }, # { # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # "commands": [ # "set interfaces ethernet eth2 description 'Configured by Ansible'", # "set interfaces ethernet eth2 vif 200", # "set interfaces ethernet eth2 vif 200 description 'VIF 200 - ETH2'", # "set interfaces ethernet eth3 description 'Configured by Ansible'", # "set interfaces ethernet eth3 mtu '1500'", # "set interfaces bonding bond1", # "set interfaces bonding bond1 description 'Bond - 1'", # "set interfaces bonding bond1 mtu '1200'", # "set interfaces vti vti2", # "set interfaces vti vti2 description 'VTI - 2'", # "set interfaces vti vti2 disable" # ] # # "after": [ # { # "description": "Bond - 1", # "enabled": true, # "mtu": 1200, # "name": "bond1" # }, # { # "enabled": true, # "name": "lo" # }, # { # "description": "VTI - 2", # "enabled": false, # "name": "vti2" # }, # { # "description": "Configured by Ansible", # "enabled": true, # "mtu": 1500, # "name": "eth3" # }, # { # "description": "Configured by Ansible", # "enabled": true, # "name": "eth2", # "vifs": [ # { # "description": "VIF 200 - ETH2", # "enabled": true, # "vlan_id": "200" # } # ] # }, # { # "enabled": true, # "name": "eth1" # }, # { # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # # ------------- # After state: # ------------- # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces bonding bond1 description 'Bond - 1' # set interfaces bonding bond1 mtu '1200' # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth2 description 'Configured by Ansible' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth2 vif 200 description 'VIF 200 - ETH2' # set interfaces ethernet eth3 description 'Configured by Ansible' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 mtu '1500' # set interfaces loopback lo # set interfaces vti vti2 description 'VTI - 2' # set interfaces vti vti2 disable # # Using replaced # # ------------- # Before state: # ------------- # # vyos:~$ show configuration commands | grep eth # set interfaces bonding bond1 description 'Bond - 1' # set interfaces bonding bond1 mtu '1400' # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 description 'Management Interface for the Appliance' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:f3:6c:b5' # set interfaces ethernet eth0 smp_affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 description 'Configured by Ansible Eng Team' # set interfaces ethernet eth1 duplex 'full' # set interfaces ethernet eth1 hw-id '08:00:27:ad:ef:65' # set interfaces ethernet eth1 smp_affinity 'auto' # set interfaces ethernet eth1 speed '100' # set interfaces ethernet eth2 description 'Configured by Ansible' # set interfaces ethernet eth2 duplex 'full' # set interfaces ethernet eth2 hw-id '08:00:27:ab:4e:79' # set interfaces ethernet eth2 mtu '500' # set interfaces ethernet eth2 smp_affinity 'auto' # set interfaces ethernet eth2 speed '100' # set interfaces ethernet eth2 vif 200 description 'Configured by Ansible' # set interfaces ethernet eth3 description 'Configured by Ansible' # set interfaces ethernet eth3 duplex 'full' # set interfaces ethernet eth3 hw-id '08:00:27:17:3c:85' # set interfaces ethernet eth3 mtu '1500' # set interfaces ethernet eth3 smp_affinity 'auto' # set interfaces ethernet eth3 speed '100' # set interfaces loopback lo # # - name: Replace device configurations of listed interfaces with provided configurations vyos_interfaces: config: - name: eth2 description: "Replaced by Ansible" - name: eth3 description: "Replaced by Ansible" - name: eth1 description: "Replaced by Ansible" state: replaced # # # ----------------------- # Module Execution Result # ----------------------- # # "before": [ # { # "description": "Bond - 1", # "enabled": true, # "mtu": 1400, # "name": "bond1" # }, # { # "enabled": true, # "name": "lo" # }, # { # "description": "Configured by Ansible", # "duplex": "full", # "enabled": true, # "mtu": 1500, # "name": "eth3", # "speed": "100" # }, # { # "description": "Configured by Ansible", # "duplex": "full", # "enabled": true, # "mtu": 500, # "name": "eth2", # "speed": "100", # "vifs": [ # { # "description": "VIF 200 - ETH2", # "enabled": true, # "vlan_id": "200" # } # ] # }, # { # "description": "Configured by Ansible Eng Team", # "duplex": "full", # "enabled": true, # "name": "eth1", # "speed": "100" # }, # { # "description": "Management Interface for the Appliance", # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # "commands": [ # "delete interfaces ethernet eth2 speed", # "delete interfaces ethernet eth2 duplex", # "delete interfaces ethernet eth2 mtu", # "delete interfaces ethernet eth2 vif 200 description", # "set interfaces ethernet eth2 description 'Replaced by Ansible'", # "delete interfaces ethernet eth3 speed", # "delete interfaces ethernet eth3 duplex", # "delete interfaces ethernet eth3 mtu", # "set interfaces ethernet eth3 description 'Replaced by Ansible'", # "delete interfaces ethernet eth1 speed", # "delete interfaces ethernet eth1 duplex", # "set interfaces ethernet eth1 description 'Replaced by Ansible'" # ] # # "after": [ # { # "description": "Bond - 1", # "enabled": true, # "mtu": 1400, # "name": "bond1" # }, # { # "enabled": true, # "name": "lo" # }, # { # "description": "Replaced by Ansible", # "enabled": true, # "name": "eth3" # }, # { # "description": "Replaced by Ansible", # "enabled": true, # "name": "eth2", # "vifs": [ # { # "enabled": true, # "vlan_id": "200" # } # ] # }, # { # "description": "Replaced by Ansible", # "enabled": true, # "name": "eth1" # }, # { # "description": "Management Interface for the Appliance", # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # # ------------- # After state: # ------------- # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces bonding bond1 description 'Bond - 1' # set interfaces bonding bond1 mtu '1400' # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 description 'Management Interface for the Appliance' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 description 'Replaced by Ansible' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth2 description 'Replaced by Ansible' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth2 vif 200 # set interfaces ethernet eth3 description 'Replaced by Ansible' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces loopback lo # # # Using overridden # # # -------------- # Before state # -------------- # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 description 'Ethernet Interface - 0' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 mtu '1200' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 description 'Configured by Ansible Eng Team' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 mtu '100' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth1 vif 100 description 'VIF 100 - ETH1' # set interfaces ethernet eth1 vif 100 disable # set interfaces ethernet eth2 description 'Configured by Ansible Team (Admin Down)' # set interfaces ethernet eth2 disable # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 mtu '600' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth3 description 'Configured by Ansible Network' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces loopback lo # set interfaces vti vti1 description 'Virtual Tunnel Interface - 1' # set interfaces vti vti1 mtu '68' # # - name: Overrides all device configuration with provided configuration vyos_interfaces: config: - name: eth0 description: Outbound Interface For The Appliance speed: auto duplex: auto - name: eth2 speed: auto duplex: auto - name: eth3 mtu: 1200 state: overridden # # # ------------------------ # Module Execution Result # ------------------------ # # "before": [ # { # "enabled": true, # "name": "lo" # }, # { # "description": "Virtual Tunnel Interface - 1", # "enabled": true, # "mtu": 68, # "name": "vti1" # }, # { # "description": "Configured by Ansible Network", # "enabled": true, # "name": "eth3" # }, # { # "description": "Configured by Ansible Team (Admin Down)", # "enabled": false, # "mtu": 600, # "name": "eth2" # }, # { # "description": "Configured by Ansible Eng Team", # "enabled": true, # "mtu": 100, # "name": "eth1", # "vifs": [ # { # "description": "VIF 100 - ETH1", # "enabled": false, # "vlan_id": "100" # } # ] # }, # { # "description": "Ethernet Interface - 0", # "duplex": "auto", # "enabled": true, # "mtu": 1200, # "name": "eth0", # "speed": "auto" # } # ] # # "commands": [ # "delete interfaces vti vti1 description", # "delete interfaces vti vti1 mtu", # "delete interfaces ethernet eth1 description", # "delete interfaces ethernet eth1 mtu", # "delete interfaces ethernet eth1 vif 100 description", # "delete interfaces ethernet eth1 vif 100 disable", # "delete interfaces ethernet eth0 mtu", # "set interfaces ethernet eth0 description 'Outbound Interface For The Appliance'", # "delete interfaces ethernet eth2 description", # "delete interfaces ethernet eth2 mtu", # "set interfaces ethernet eth2 duplex 'auto'", # "delete interfaces ethernet eth2 disable", # "set interfaces ethernet eth2 speed 'auto'", # "delete interfaces ethernet eth3 description", # "set interfaces ethernet eth3 mtu '1200'" # ], # # "after": [ # { # "enabled": true, # "name": "lo" # }, # { # "enabled": true, # "name": "vti1" # }, # { # "enabled": true, # "mtu": 1200, # "name": "eth3" # }, # { # "duplex": "auto", # "enabled": true, # "name": "eth2", # "speed": "auto" # }, # { # "enabled": true, # "name": "eth1", # "vifs": [ # { # "enabled": true, # "vlan_id": "100" # } # ] # }, # { # "description": "Outbound Interface For The Appliance", # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # # ------------ # After state # ------------ # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 description 'Outbound Interface For The Appliance' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth1 vif 100 # set interfaces ethernet eth2 duplex 'auto' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth2 speed 'auto' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 mtu '1200' # set interfaces loopback lo # set interfaces vti vti1 # # # Using deleted # # # ------------- # Before state # ------------- # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces bonding bond0 mtu '1300' # set interfaces bonding bond1 description 'LAG - 1' # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 description 'Outbound Interface for this appliance' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 description 'Configured by Ansible Network' # set interfaces ethernet eth1 duplex 'full' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth1 speed '100' # set interfaces ethernet eth2 description 'Configured by Ansible' # set interfaces ethernet eth2 disable # set interfaces ethernet eth2 duplex 'full' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 mtu '600' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth2 speed '100' # set interfaces ethernet eth3 description 'Configured by Ansible Network' # set interfaces ethernet eth3 duplex 'full' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 speed '100' # set interfaces loopback lo # # - name: Delete attributes of given interfaces (Note - This won't delete the interfaces themselves) vyos_interfaces: config: - name: bond1 - name: eth1 - name: eth2 - name: eth3 state: deleted # # # ------------------------ # Module Execution Results # ------------------------ # # "before": [ # { # "enabled": true, # "mtu": 1300, # "name": "bond0" # }, # { # "description": "LAG - 1", # "enabled": true, # "name": "bond1" # }, # { # "enabled": true, # "name": "lo" # }, # { # "description": "Configured by Ansible Network", # "duplex": "full", # "enabled": true, # "name": "eth3", # "speed": "100" # }, # { # "description": "Configured by Ansible", # "duplex": "full", # "enabled": false, # "mtu": 600, # "name": "eth2", # "speed": "100" # }, # { # "description": "Configured by Ansible Network", # "duplex": "full", # "enabled": true, # "name": "eth1", # "speed": "100" # }, # { # "description": "Outbound Interface for this appliance", # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # "commands": [ # "delete interfaces bonding bond1 description", # "delete interfaces ethernet eth1 speed", # "delete interfaces ethernet eth1 duplex", # "delete interfaces ethernet eth1 description", # "delete interfaces ethernet eth2 speed", # "delete interfaces ethernet eth2 disable", # "delete interfaces ethernet eth2 duplex", # "delete interfaces ethernet eth2 disable", # "delete interfaces ethernet eth2 description", # "delete interfaces ethernet eth2 disable", # "delete interfaces ethernet eth2 mtu", # "delete interfaces ethernet eth2 disable", # "delete interfaces ethernet eth3 speed", # "delete interfaces ethernet eth3 duplex", # "delete interfaces ethernet eth3 description" # ] # # "after": [ # { # "enabled": true, # "mtu": 1300, # "name": "bond0" # }, # { # "enabled": true, # "name": "bond1" # }, # { # "enabled": true, # "name": "lo" # }, # { # "enabled": true, # "name": "eth3" # }, # { # "enabled": true, # "name": "eth2" # }, # { # "enabled": true, # "name": "eth1" # }, # { # "description": "Outbound Interface for this appliance", # "duplex": "auto", # "enabled": true, # "name": "eth0", # "speed": "auto" # } # ] # # # ------------ # After state # ------------ # # vyos@vyos:~$ show configuration commands | grep interfaces # set interfaces bonding bond0 mtu '1300' # set interfaces bonding bond1 # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 description 'Outbound Interface for this appliance' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:ea:0f:b9' # set interfaces ethernet eth1 smp-affinity 'auto' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth2 smp-affinity 'auto' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces loopback lo # # """ RETURN = """ before: description: The configuration as structured data prior to module invocation. returned: always sample: > The configuration returned will always be in the same format of the parameters above. type: list after: description: The configuration as structured data after module completion. returned: when changed sample: > The configuration returned will always be in the same format of the parameters above. type: list commands: description: The set of commands pushed to the remote device. returned: always type: list sample: - 'set interfaces ethernet eth1 mtu 1200' - 'set interfaces ethernet eth2 vif 100 description VIF 100' """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.interfaces.interfaces import ( InterfacesArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.interfaces.interfaces import ( Interfaces, ) def main(): """ Main entry point for module execution :returns: the result form module invocation """ module = AnsibleModule( argument_spec=InterfacesArgs.argument_spec, supports_check_mode=True ) result = Interfaces(module).execute_module() module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_l3_interface.py b/plugins/modules/vyos_l3_interface.py deleted file mode 120000 index 961ef4e..0000000 --- a/plugins/modules/vyos_l3_interface.py +++ /dev/null @@ -1 +0,0 @@ -_vyos_l3_interface.py \ No newline at end of file diff --git a/plugins/modules/vyos_l3_interface.py b/plugins/modules/vyos_l3_interface.py new file mode 100644 index 0000000..faa9629 --- /dev/null +++ b/plugins/modules/vyos_l3_interface.py @@ -0,0 +1,329 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2017, Ansible by Red Hat, inc +# +# This file is part of Ansible by Red Hat +# +# 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 . +# + +ANSIBLE_METADATA = { + "metadata_version": "1.1", + "status": ["deprecated"], + "supported_by": "network", +} + + +DOCUMENTATION = """module: vyos_l3_interface +author: Ricardo Carrillo Cruz (@rcarrillocruz) +short_description: Manage L3 interfaces on VyOS network devices +description: +- This module provides declarative management of L3 interfaces on VyOS network devices. +deprecated: + removed_in: '2.13' + alternative: vyos_l3_interfaces + why: Updated modules released with more functionality. +notes: +- Tested against VYOS 1.1.7 +options: + name: + description: + - Name of the L3 interface. + ipv4: + description: + - IPv4 of the L3 interface. + ipv6: + description: + - IPv6 of the L3 interface. + aggregate: + description: List of L3 interfaces definitions + state: + description: + - State of the L3 interface configuration. + default: present + choices: + - present + - absent +extends_documentation_fragment: +- vyos.vyos.vyos +""" + +EXAMPLES = """ +- name: Set eth0 IPv4 address + vyos_l3_interface: + name: eth0 + ipv4: 192.168.0.1/24 + +- name: Remove eth0 IPv4 address + vyos_l3_interface: + name: eth0 + state: absent + +- name: Set IP addresses on aggregate + vyos_l3_interface: + aggregate: + - { name: eth1, ipv4: 192.168.2.10/24 } + - { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" } + +- name: Remove IP addresses on aggregate + vyos_l3_interface: + aggregate: + - { name: eth1, ipv4: 192.168.2.10/24 } + - { name: eth2, ipv4: 192.168.3.10/24, ipv6: "fd5d:12c9:2201:1::1/64" } + state: absent +""" + +RETURN = """ +commands: + description: The list of configuration mode commands to send to the device + returned: always, except for the platforms that use Netconf transport to manage the device. + type: list + sample: + - set interfaces ethernet eth0 address '192.168.0.1/24' +""" + +import socket +import re + +from copy import deepcopy + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + is_masklen, + validate_ip_address, +) +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + remove_default_spec, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + load_config, + run_commands, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + vyos_argument_spec, +) + + +def is_ipv4(value): + if value: + address = value.split("/") + if is_masklen(address[1]) and validate_ip_address(address[0]): + return True + return False + + +def is_ipv6(value): + if value: + address = value.split("/") + if 0 <= int(address[1]) <= 128: + try: + socket.inet_pton(socket.AF_INET6, address[0]) + except socket.error: + return False + return True + return False + + +def search_obj_in_list(name, lst): + for o in lst: + if o["name"] == name: + return o + + return None + + +def map_obj_to_commands(updates, module): + commands = list() + want, have = updates + + for w in want: + name = w["name"] + ipv4 = w["ipv4"] + ipv6 = w["ipv6"] + state = w["state"] + + obj_in_have = search_obj_in_list(name, have) + + if state == "absent" and obj_in_have: + if ( + not ipv4 + and not ipv6 + and (obj_in_have["ipv4"] or obj_in_have["ipv6"]) + ): + if name == "lo": + commands.append("delete interfaces loopback lo address") + else: + commands.append( + "delete interfaces ethernet " + name + " address" + ) + else: + if ipv4 and ipv4 in obj_in_have["ipv4"]: + if name == "lo": + commands.append( + "delete interfaces loopback lo address " + ipv4 + ) + else: + commands.append( + "delete interfaces ethernet " + + name + + " address " + + ipv4 + ) + if ipv6 and ipv6 in obj_in_have["ipv6"]: + if name == "lo": + commands.append( + "delete interfaces loopback lo address " + ipv6 + ) + else: + commands.append( + "delete interfaces ethernet " + + name + + " address " + + ipv6 + ) + elif state == "present" and obj_in_have: + if ipv4 and ipv4 not in obj_in_have["ipv4"]: + if name == "lo": + commands.append( + "set interfaces loopback lo address " + ipv4 + ) + else: + commands.append( + "set interfaces ethernet " + name + " address " + ipv4 + ) + + if ipv6 and ipv6 not in obj_in_have["ipv6"]: + if name == "lo": + commands.append( + "set interfaces loopback lo address " + ipv6 + ) + else: + commands.append( + "set interfaces ethernet " + name + " address " + ipv6 + ) + + return commands + + +def map_config_to_obj(module): + obj = [] + output = run_commands(module, ["show interfaces"]) + lines = re.split(r"\n[e|l]", output[0])[1:] + + if len(lines) > 0: + for line in lines: + splitted_line = line.split() + + if len(splitted_line) > 0: + ipv4 = [] + ipv6 = [] + + if splitted_line[0].lower().startswith("th"): + name = "e" + splitted_line[0].lower() + elif splitted_line[0].lower().startswith("o"): + name = "l" + splitted_line[0].lower() + + for i in splitted_line[1:]: + if ("." in i or ":" in i) and "/" in i: + value = i.split(r"\n")[0] + if is_ipv4(value): + ipv4.append(value) + elif is_ipv6(value): + ipv6.append(value) + + obj.append({"name": name, "ipv4": ipv4, "ipv6": ipv6}) + + return obj + + +def map_params_to_obj(module): + obj = [] + + aggregate = module.params.get("aggregate") + if aggregate: + for item in aggregate: + for key in item: + if item.get(key) is None: + item[key] = module.params[key] + + obj.append(item.copy()) + else: + obj.append( + { + "name": module.params["name"], + "ipv4": module.params["ipv4"], + "ipv6": module.params["ipv6"], + "state": module.params["state"], + } + ) + + return obj + + +def main(): + """ main entry point for module execution + """ + element_spec = dict( + name=dict(), + ipv4=dict(), + ipv6=dict(), + state=dict(default="present", choices=["present", "absent"]), + ) + + aggregate_spec = deepcopy(element_spec) + aggregate_spec["name"] = dict(required=True) + + # remove default in aggregate spec, to handle common arguments + remove_default_spec(aggregate_spec) + + argument_spec = dict( + aggregate=dict(type="list", elements="dict", options=aggregate_spec), + ) + + argument_spec.update(element_spec) + argument_spec.update(vyos_argument_spec) + + required_one_of = [["name", "aggregate"]] + mutually_exclusive = [["name", "aggregate"]] + module = AnsibleModule( + argument_spec=argument_spec, + required_one_of=required_one_of, + mutually_exclusive=mutually_exclusive, + supports_check_mode=True, + ) + + warnings = list() + + result = {"changed": False} + + if warnings: + result["warnings"] = warnings + + want = map_params_to_obj(module) + have = map_config_to_obj(module) + + commands = map_obj_to_commands((want, have), module) + result["commands"] = commands + + if commands: + commit = not module.check_mode + load_config(module, commands, commit=commit) + result["changed"] = True + + module.exit_json(**result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/vyos_l3_interfaces.py b/plugins/modules/vyos_l3_interfaces.py index 113ea53..a77ecaf 100644 --- a/plugins/modules/vyos_l3_interfaces.py +++ b/plugins/modules/vyos_l3_interfaces.py @@ -1,381 +1,377 @@ #!/usr/bin/python # -*- 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) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The module file for vyos_l3_interfaces """ from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_l3_interfaces -version_added: 2.9 +DOCUMENTATION = """module: vyos_l3_interfaces short_description: Manages L3 interface attributes of VyOS network devices. description: This module manages the L3 interface attributes on VyOS network devices. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). author: Nilashish Chakraborty (@NilashishC) options: config: description: The provided L3 interfaces configuration. type: list elements: dict suboptions: name: description: - - Full name of the interface, e.g. eth0, eth1. + - Full name of the interface, e.g. eth0, eth1. type: str - required: True + required: true ipv4: description: - - List of IPv4 addresses of the interface. + - List of IPv4 addresses of the interface. type: list elements: dict suboptions: address: description: - - IPv4 address of the interface. + - IPv4 address of the interface. type: str ipv6: description: - - List of IPv6 addresses of the interface. + - List of IPv6 addresses of the interface. type: list elements: dict suboptions: address: description: - - IPv6 address of the interface. + - IPv6 address of the interface. type: str vifs: description: - - Virtual sub-interfaces L3 configurations. + - Virtual sub-interfaces L3 configurations. elements: dict type: list suboptions: vlan_id: description: - - Identifier for the virtual sub-interface. + - Identifier for the virtual sub-interface. type: int ipv4: description: - - List of IPv4 addresses of the virtual interface. + - List of IPv4 addresses of the virtual interface. type: list elements: dict suboptions: address: description: - - IPv4 address of the virtual interface. + - IPv4 address of the virtual interface. type: str ipv6: description: - - List of IPv6 addresses of the virtual interface. + - List of IPv6 addresses of the virtual interface. type: list elements: dict suboptions: address: description: - - IPv6 address of the virtual interface. + - IPv6 address of the virtual interface. type: str state: description: - - The state of the configuration after module completion. + - The state of the configuration after module completion. type: str choices: - merged - replaced - overridden - deleted default: merged - """ EXAMPLES = """ # Using merged # # Before state: # ------------- # # vyos:~$ show configuration commands | grep -e eth[2,3] # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 vif 101 # set interfaces ethernet eth3 vif 102 - name: Merge provided configuration with device configuration vyos_l3_interfaces: config: - name: eth2 ipv4: - address: 192.0.2.10/28 - address: 198.51.100.40/27 ipv6: - address: 2001:db8:100::2/32 - address: 2001:db8:400::10/32 - name: eth3 ipv4: - address: 203.0.113.65/26 vifs: - vlan_id: 101 ipv4: - address: 192.0.2.71/28 - address: 198.51.100.131/25 - vlan_id: 102 ipv6: - address: 2001:db8:1000::5/38 - address: 2001:db8:1400::3/38 state: merged # After state: # ------------- # # vyos:~$ show configuration commands | grep -e eth[2,3] # set interfaces ethernet eth2 address '192.0.2.10/28' # set interfaces ethernet eth2 address '198.51.100.40/27' # set interfaces ethernet eth2 address '2001:db8:100::2/32' # set interfaces ethernet eth2 address '2001:db8:400::10/32' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 address '203.0.113.65/26' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 vif 101 address '192.0.2.71/28' # set interfaces ethernet eth3 vif 101 address '198.51.100.131/25' # set interfaces ethernet eth3 vif 102 address '2001:db8:1000::5/38' # set interfaces ethernet eth3 vif 102 address '2001:db8:1400::3/38' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::2/34' # Using replaced # # Before state: # ------------- # # vyos:~$ show configuration commands | grep eth # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:EA:0F:B9' # set interfaces ethernet eth1 address '192.0.2.14/24' # set interfaces ethernet eth2 address '192.0.2.10/24' # set interfaces ethernet eth2 address '192.0.2.11/24' # set interfaces ethernet eth2 address '2001:db8::10/32' # set interfaces ethernet eth2 address '2001:db8::11/32' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 address '198.51.100.10/24' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 vif 101 address '198.51.100.130/25' # set interfaces ethernet eth3 vif 101 address '198.51.100.131/25' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::3/34' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::2/34' # - name: Replace device configurations of listed interfaces with provided configurations vyos_l3_interfaces: config: - name: eth2 ipv4: - address: 192.0.2.10/24 - name: eth3 ipv6: - address: 2001:db8::11/32 state: replaced # After state: # ------------- # # vyos:~$ show configuration commands | grep eth # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:EA:0F:B9' # set interfaces ethernet eth1 address '192.0.2.14/24' # set interfaces ethernet eth2 address '192.0.2.10/24' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 address '2001:db8::11/32' # set interfaces ethernet eth3 vif 101 # set interfaces ethernet eth3 vif 102 # Using overridden # # Before state # -------------- # # vyos@vyos-appliance:~$ show configuration commands | grep eth # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:EA:0F:B9' # set interfaces ethernet eth1 address '192.0.2.14/24' # set interfaces ethernet eth2 address '192.0.2.10/24' # set interfaces ethernet eth2 address '192.0.2.11/24' # set interfaces ethernet eth2 address '2001:db8::10/32' # set interfaces ethernet eth2 address '2001:db8::11/32' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 address '198.51.100.10/24' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 vif 101 address '198.51.100.130/25' # set interfaces ethernet eth3 vif 101 address '198.51.100.131/25' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::3/34' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::2/34' - name: Overrides all device configuration with provided configuration vyos_l3_interfaces: config: - name: eth0 ipv4: - address: dhcp ipv6: - address: dhcpv6 state: overridden # After state # ------------ # # vyos@vyos-appliance:~$ show configuration commands | grep eth # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 address 'dhcpv6' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:EA:0F:B9' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 vif 101 # set interfaces ethernet eth3 vif 102 # Using deleted # # Before state # ------------- # vyos@vyos-appliance:~$ show configuration commands | grep eth # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:30:f0:22' # set interfaces ethernet eth0 smp-affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:EA:0F:B9' # set interfaces ethernet eth1 address '192.0.2.14/24' # set interfaces ethernet eth2 address '192.0.2.10/24' # set interfaces ethernet eth2 address '192.0.2.11/24' # set interfaces ethernet eth2 address '2001:db8::10/32' # set interfaces ethernet eth2 address '2001:db8::11/32' # set interfaces ethernet eth2 hw-id '08:00:27:c2:98:23' # set interfaces ethernet eth3 address '198.51.100.10/24' # set interfaces ethernet eth3 hw-id '08:00:27:43:70:8c' # set interfaces ethernet eth3 vif 101 address '198.51.100.130/25' # set interfaces ethernet eth3 vif 101 address '198.51.100.131/25' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::3/34' # set interfaces ethernet eth3 vif 102 address '2001:db8:4000::2/34' - name: Delete L3 attributes of given interfaces (Note - This won't delete the interface itself) vyos_l3_interfaces: config: - name: eth1 - name: eth2 - name: eth3 state: deleted # After state # ------------ # vyos@vyos-appliance:~$ show configuration commands | grep eth # set interfaces ethernet eth0 address 'dhcp' # set interfaces ethernet eth0 duplex 'auto' # set interfaces ethernet eth0 hw-id '08:00:27:f3:6c:b5' # set interfaces ethernet eth0 smp_affinity 'auto' # set interfaces ethernet eth0 speed 'auto' # set interfaces ethernet eth1 hw-id '08:00:27:ad:ef:65' # set interfaces ethernet eth1 smp_affinity 'auto' # set interfaces ethernet eth2 hw-id '08:00:27:ab:4e:79' # set interfaces ethernet eth2 smp_affinity 'auto' # set interfaces ethernet eth3 hw-id '08:00:27:17:3c:85' # set interfaces ethernet eth3 smp_affinity 'auto' """ RETURN = """ before: description: The configuration as structured data prior to module invocation. returned: always type: list sample: > The configuration returned will always be in the same format of the parameters above. after: description: The configuration as structured data after module completion. returned: when changed type: list sample: > The configuration returned will always be in the same format of the parameters above. commands: description: The set of commands pushed to the remote device. returned: always type: list sample: ['set interfaces ethernet eth1 192.0.2.14/2', 'set interfaces ethernet eth3 vif 101 address 198.51.100.130/25'] """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.l3_interfaces.l3_interfaces import ( L3_interfacesArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.l3_interfaces.l3_interfaces import ( L3_interfaces, ) def main(): """ Main entry point for module execution :returns: the result form module invocation """ module = AnsibleModule( argument_spec=L3_interfacesArgs.argument_spec, supports_check_mode=True ) result = L3_interfaces(module).execute_module() module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_lag_interfaces.py b/plugins/modules/vyos_lag_interfaces.py index 5c9b4c1..84f3d01 100644 --- a/plugins/modules/vyos_lag_interfaces.py +++ b/plugins/modules/vyos_lag_interfaces.py @@ -1,570 +1,567 @@ #!/usr/bin/python # -*- 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) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The module file for vyos_lag_interfaces """ from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_lag_interfaces -version_added: 2.9 +DOCUMENTATION = """module: vyos_lag_interfaces short_description: Manages attributes of link aggregation groups on VyOS network devices. -description: This module manages attributes of link aggregation groups on VyOS network devices. +description: This module manages attributes of link aggregation groups on VyOS network + devices. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). author: Rohit Thakur (@rohitthakur2590) options: config: description: A list of link aggregation group configurations. type: list suboptions: name: description: - - Name of the link aggregation group (LAG) or bond. + - Name of the link aggregation group (LAG) or bond. type: str - required: True + required: true mode: description: - - LAG or bond mode. + - LAG or bond mode. type: str choices: - - 802.3ad - - active-backup - - broadcast - - round-robin - - transmit-load-balance - - adaptive-load-balance - - xor-hash + - 802.3ad + - active-backup + - broadcast + - round-robin + - transmit-load-balance + - adaptive-load-balance + - xor-hash members: description: - - List of member interfaces for the LAG (bond). + - List of member interfaces for the LAG (bond). type: list suboptions: member: description: - - Name of the member interface. + - Name of the member interface. type: str primary: description: - - Primary device interfaces for the LAG (bond). + - Primary device interfaces for the LAG (bond). type: str hash_policy: description: - - LAG or bonding transmit hash policy. + - LAG or bonding transmit hash policy. type: str choices: - - layer2 - - layer2+3 - - layer3+4 + - layer2 + - layer2+3 + - layer3+4 arp_monitor: description: - - ARP Link monitoring parameters. + - ARP Link monitoring parameters. type: dict suboptions: interval: description: - - ARP link monitoring frequency in milliseconds. + - ARP link monitoring frequency in milliseconds. type: int target: description: - - IP address to use for ARP monitoring. + - IP address to use for ARP monitoring. type: list state: description: - - The state of the configuration after module completion. + - The state of the configuration after module completion. type: str choices: - merged - replaced - overridden - deleted default: merged - """ EXAMPLES = """ # Using merged # # Before state: # ------------- # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 # set interfaces bonding bond3 # - name: Merge provided configuration with device configuration vyos_lag_interfaces: config: - name: bond2 mode: active-backup members: - member: eth2 - member: eth1 hash_policy: layer2 primary: eth2 - name: 'bond3' mode: 'active-backup' hash_policy: 'layer2+3' members: - member: eth3 primary: 'eth3' state: merged # # # ------------------------- # Module Execution Result # ------------------------- # # "before": [ # { # "name": "bond2" # }, # { # "name": "bond3" # } # ], # # "commands": [ # "set interfaces bonding bond2 hash-policy 'layer2'", # "set interfaces bonding bond2 mode 'active-backup'", # "set interfaces ethernet eth2 bond-group bond2", # "set interfaces ethernet eth1 bond-group bond2", # "set interfaces bonding bond2 primary 'eth2'", # "set interfaces bonding bond3 hash-policy 'layer2+3'", # "set interfaces bonding bond3 mode 'active-backup'", # "set interfaces ethernet eth3 bond-group bond3", # "set interfaces bonding bond3 primary 'eth3'" # ] # # "after": [ # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth1" # }, # { # "member": "eth2" # } # ], # "mode": "active-backup", # "name": "bond2", # "primary": "eth2" # }, # { # "hash_policy": "layer2+3", # "members": [ # { # "member": "eth3" # } # ], # "mode": "active-backup", # "name": "bond3", # "primary": "eth3" # } # ] # # After state: # ------------- # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 hash-policy 'layer2' # set interfaces bonding bond2 mode 'active-backup' # set interfaces bonding bond2 primary 'eth2' # set interfaces bonding bond3 hash-policy 'layer2+3' # set interfaces bonding bond3 mode 'active-backup' # set interfaces bonding bond3 primary 'eth3' # set interfaces ethernet eth1 bond-group 'bond2' # set interfaces ethernet eth2 bond-group 'bond2' # set interfaces ethernet eth3 bond-group 'bond3' # Using replaced # # Before state: # ------------- # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 hash-policy 'layer2' # set interfaces bonding bond2 mode 'active-backup' # set interfaces bonding bond2 primary 'eth2' # set interfaces bonding bond3 hash-policy 'layer2+3' # set interfaces bonding bond3 mode 'active-backup' # set interfaces bonding bond3 primary 'eth3' # set interfaces ethernet eth1 bond-group 'bond2' # set interfaces ethernet eth2 bond-group 'bond2' # set interfaces ethernet eth3 bond-group 'bond3' # - name: Replace device configurations of listed LAGs with provided configurations vyos_lag_interfaces: config: - name: bond3 mode: '802.3ad' hash_policy: 'layer2' members: - member: eth3 state: replaced # # # ------------------------- # Module Execution Result # ------------------------- # # "before": [ # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth1" # }, # { # "member": "eth2" # } # ], # "mode": "active-backup", # "name": "bond2", # "primary": "eth2" # }, # { # "hash_policy": "layer2+3", # "members": [ # { # "member": "eth3" # } # ], # "mode": "active-backup", # "name": "bond3", # "primary": "eth3" # } # ], # # "commands": [ # "delete interfaces bonding bond3 primary", # "set interfaces bonding bond3 hash-policy 'layer2'", # "set interfaces bonding bond3 mode '802.3ad'" # ], # # "after": [ # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth1" # }, # { # "member": "eth2" # } # ], # "mode": "active-backup", # "name": "bond2", # "primary": "eth2" # }, # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth3" # } # ], # "mode": "802.3ad", # "name": "bond3" # } # ], # # After state: # ------------- # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 hash-policy 'layer2' # set interfaces bonding bond2 mode 'active-backup' # set interfaces bonding bond2 primary 'eth2' # set interfaces bonding bond3 hash-policy 'layer2' # set interfaces bonding bond3 mode '802.3ad' # set interfaces ethernet eth1 bond-group 'bond2' # set interfaces ethernet eth2 bond-group 'bond2' # set interfaces ethernet eth3 bond-group 'bond3' # Using overridden # # Before state # -------------- # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 hash-policy 'layer2' # set interfaces bonding bond2 mode 'active-backup' # set interfaces bonding bond2 primary 'eth2' # set interfaces bonding bond3 hash-policy 'layer2' # set interfaces bonding bond3 mode '802.3ad' # set interfaces ethernet eth1 bond-group 'bond2' # set interfaces ethernet eth2 bond-group 'bond2' # set interfaces ethernet eth3 bond-group 'bond3' # - name: Overrides all device configuration with provided configuration vyos_lag_interfaces: config: - name: bond3 mode: active-backup members: - member: eth1 - member: eth2 - member: eth3 primary: eth3 hash_policy: layer2 state: overridden # # # ------------------------- # Module Execution Result # ------------------------- # # "before": [ # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth1" # }, # { # "member": "eth2" # } # ], # "mode": "active-backup", # "name": "bond2", # "primary": "eth2" # }, # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth3" # } # ], # "mode": "802.3ad", # "name": "bond3" # } # ], # # "commands": [ # "delete interfaces bonding bond2 hash-policy", # "delete interfaces ethernet eth1 bond-group bond2", # "delete interfaces ethernet eth2 bond-group bond2", # "delete interfaces bonding bond2 mode", # "delete interfaces bonding bond2 primary", # "set interfaces bonding bond3 mode 'active-backup'", # "set interfaces ethernet eth1 bond-group bond3", # "set interfaces ethernet eth2 bond-group bond3", # "set interfaces bonding bond3 primary 'eth3'" # ], # # "after": [ # { # "name": "bond2" # }, # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth1" # }, # { # "member": "eth2" # }, # { # "member": "eth3" # } # ], # "mode": "active-backup", # "name": "bond3", # "primary": "eth3" # } # ], # # # After state # ------------ # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 # set interfaces bonding bond3 hash-policy 'layer2' # set interfaces bonding bond3 mode 'active-backup' # set interfaces bonding bond3 primary 'eth3' # set interfaces ethernet eth1 bond-group 'bond3' # set interfaces ethernet eth2 bond-group 'bond3' # set interfaces ethernet eth3 bond-group 'bond3' # Using deleted # # Before state # ------------- # # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 hash-policy 'layer2' # set interfaces bonding bond2 mode 'active-backup' # set interfaces bonding bond2 primary 'eth2' # set interfaces bonding bond3 hash-policy 'layer2+3' # set interfaces bonding bond3 mode 'active-backup' # set interfaces bonding bond3 primary 'eth3' # set interfaces ethernet eth1 bond-group 'bond2' # set interfaces ethernet eth2 bond-group 'bond2' # set interfaces ethernet eth3 bond-group 'bond3' # - name: Delete LAG attributes of given interfaces (Note This won't delete the interface itself) vyos_lag_interfaces: config: - name: bond2 - name: bond3 state: deleted # # # ------------------------ # Module Execution Results # ------------------------ # # "before": [ # { # "hash_policy": "layer2", # "members": [ # { # "member": "eth1" # }, # { # "member": "eth2" # } # ], # "mode": "active-backup", # "name": "bond2", # "primary": "eth2" # }, # { # "hash_policy": "layer2+3", # "members": [ # { # "member": "eth3" # } # ], # "mode": "active-backup", # "name": "bond3", # "primary": "eth3" # } # ], # "commands": [ # "delete interfaces bonding bond2 hash-policy", # "delete interfaces ethernet eth1 bond-group bond2", # "delete interfaces ethernet eth2 bond-group bond2", # "delete interfaces bonding bond2 mode", # "delete interfaces bonding bond2 primary", # "delete interfaces bonding bond3 hash-policy", # "delete interfaces ethernet eth3 bond-group bond3", # "delete interfaces bonding bond3 mode", # "delete interfaces bonding bond3 primary" # ], # # "after": [ # { # "name": "bond2" # }, # { # "name": "bond3" # } # ], # # After state # ------------ # vyos@vyos:~$ show configuration commands | grep bond # set interfaces bonding bond2 # set interfaces bonding bond3 """ RETURN = """ before: description: The configuration as structured data prior to module invocation. returned: always type: list sample: > The configuration returned will always be in the same format of the parameters above. after: description: The configuration as structured data after module completion. returned: when changed type: list sample: > The configuration returned will always be in the same format of the parameters above. commands: description: The set of commands pushed to the remote device. returned: always type: list sample: - 'set interfaces bonding bond2' - 'set interfaces bonding bond2 hash-policy layer2' """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.lag_interfaces.lag_interfaces import ( Lag_interfacesArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.lag_interfaces.lag_interfaces import ( Lag_interfaces, ) def main(): """ Main entry point for module execution :returns: the result form module invocation """ required_if = [ ("state", "merged", ("config",)), ("state", "replaced", ("config",)), ("state", "overridden", ("config",)), ] module = AnsibleModule( argument_spec=Lag_interfacesArgs.argument_spec, required_if=required_if, supports_check_mode=True, ) result = Lag_interfaces(module).execute_module() module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_linkagg.py b/plugins/modules/vyos_linkagg.py deleted file mode 120000 index 294bec1..0000000 --- a/plugins/modules/vyos_linkagg.py +++ /dev/null @@ -1 +0,0 @@ -_vyos_linkagg.py \ No newline at end of file diff --git a/plugins/modules/vyos_linkagg.py b/plugins/modules/vyos_linkagg.py new file mode 100644 index 0000000..6810a54 --- /dev/null +++ b/plugins/modules/vyos_linkagg.py @@ -0,0 +1,327 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2017, Ansible by Red Hat, inc +# +# This file is part of Ansible by Red Hat +# +# 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 . +# + +ANSIBLE_METADATA = { + "metadata_version": "1.1", + "status": ["deprecated"], + "supported_by": "network", +} + + +DOCUMENTATION = """module: vyos_linkagg +author: Ricardo Carrillo Cruz (@rcarrillocruz) +short_description: Manage link aggregation groups on VyOS network devices +description: +- This module provides declarative management of link aggregation groups on VyOS network + devices. +deprecated: + removed_in: '2.13' + alternative: vyos_lag_interfaces + why: Updated modules released with more functionality. +notes: +- Tested against VYOS 1.1.7 +options: + name: + description: + - Name of the link aggregation group. + required: true + type: str + mode: + description: + - Mode of the link aggregation group. + choices: + - 802.3ad + - active-backup + - broadcast + - round-robin + - transmit-load-balance + - adaptive-load-balance + - xor-hash + - 'on' + type: str + members: + description: + - List of members of the link aggregation group. + type: list + aggregate: + description: List of link aggregation definitions. + type: list + state: + description: + - State of the link aggregation group. + default: present + choices: + - present + - absent + - up + - down + type: str +extends_documentation_fragment: +- vyos.vyos.vyos +""" + +EXAMPLES = """ +- name: configure link aggregation group + vyos_linkagg: + name: bond0 + members: + - eth0 + - eth1 + +- name: remove configuration + vyos_linkagg: + name: bond0 + state: absent + +- name: Create aggregate of linkagg definitions + vyos_linkagg: + aggregate: + - { name: bond0, members: [eth1] } + - { name: bond1, members: [eth2] } + +- name: Remove aggregate of linkagg definitions + vyos_linkagg: + aggregate: + - name: bond0 + - name: bond1 + state: absent +""" + +RETURN = """ +commands: + description: The list of configuration mode commands to send to the device + returned: always, except for the platforms that use Netconf transport to manage the device. + type: list + sample: + - set interfaces bonding bond0 + - set interfaces ethernet eth0 bond-group 'bond0' + - set interfaces ethernet eth1 bond-group 'bond0' +""" +from copy import deepcopy + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + remove_default_spec, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + load_config, + run_commands, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + vyos_argument_spec, +) + + +def search_obj_in_list(name, lst): + for o in lst: + if o["name"] == name: + return o + + return None + + +def map_obj_to_commands(updates, module): + commands = list() + want, have = updates + + for w in want: + name = w["name"] + members = w.get("members") or [] + mode = w["mode"] + + if mode == "on": + mode = "802.3ad" + + state = w["state"] + + obj_in_have = search_obj_in_list(name, have) + + if state == "absent": + if obj_in_have: + for m in obj_in_have["members"]: + commands.append( + "delete interfaces ethernet " + m + " bond-group" + ) + + commands.append("delete interfaces bonding " + name) + else: + if not obj_in_have: + commands.append( + "set interfaces bonding " + name + " mode " + mode + ) + + for m in members: + commands.append( + "set interfaces ethernet " + m + " bond-group " + name + ) + + if state == "down": + commands.append( + "set interfaces bonding " + name + " disable" + ) + else: + if mode != obj_in_have["mode"]: + commands.append( + "set interfaces bonding " + name + " mode " + mode + ) + + missing_members = list( + set(members) - set(obj_in_have["members"]) + ) + for m in missing_members: + commands.append( + "set interfaces ethernet " + m + " bond-group " + name + ) + + if state == "down" and obj_in_have["state"] == "up": + commands.append( + "set interfaces bonding " + name + " disable" + ) + elif state == "up" and obj_in_have["state"] == "down": + commands.append( + "delete interfaces bonding " + name + " disable" + ) + + return commands + + +def map_config_to_obj(module): + obj = [] + output = run_commands(module, ["show interfaces bonding slaves"]) + lines = output[0].splitlines() + + if len(lines) > 1: + for line in lines[1:]: + splitted_line = line.split() + + name = splitted_line[0] + mode = splitted_line[1] + state = splitted_line[2] + + if len(splitted_line) > 4: + members = splitted_line[4:] + else: + members = [] + + obj.append( + { + "name": name, + "mode": mode, + "members": members, + "state": state, + } + ) + + return obj + + +def map_params_to_obj(module): + obj = [] + aggregate = module.params.get("aggregate") + if aggregate: + for item in aggregate: + for key in item: + if item.get(key) is None: + item[key] = module.params[key] + + obj.append(item.copy()) + else: + obj.append( + { + "name": module.params["name"], + "mode": module.params["mode"], + "members": module.params["members"], + "state": module.params["state"], + } + ) + + return obj + + +def main(): + """ main entry point for module execution + """ + element_spec = dict( + name=dict(), + mode=dict( + choices=[ + "802.3ad", + "active-backup", + "broadcast", + "round-robin", + "transmit-load-balance", + "adaptive-load-balance", + "xor-hash", + "on", + ], + default="802.3ad", + ), + members=dict(type="list"), + state=dict( + default="present", choices=["present", "absent", "up", "down"] + ), + ) + + aggregate_spec = deepcopy(element_spec) + aggregate_spec["name"] = dict(required=True) + + # remove default in aggregate spec, to handle common arguments + remove_default_spec(aggregate_spec) + + argument_spec = dict( + aggregate=dict(type="list", elements="dict", options=aggregate_spec), + ) + + argument_spec.update(element_spec) + argument_spec.update(vyos_argument_spec) + + required_one_of = [["name", "aggregate"]] + mutually_exclusive = [["name", "aggregate"]] + module = AnsibleModule( + argument_spec=argument_spec, + required_one_of=required_one_of, + mutually_exclusive=mutually_exclusive, + supports_check_mode=True, + ) + + warnings = list() + + result = {"changed": False} + + if warnings: + result["warnings"] = warnings + + want = map_params_to_obj(module) + have = map_config_to_obj(module) + + commands = map_obj_to_commands((want, have), module) + result["commands"] = commands + + if commands: + commit = not module.check_mode + load_config(module, commands, commit=commit) + result["changed"] = True + + module.exit_json(**result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/vyos_lldp.py b/plugins/modules/vyos_lldp.py deleted file mode 120000 index 259de8c..0000000 --- a/plugins/modules/vyos_lldp.py +++ /dev/null @@ -1 +0,0 @@ -_vyos_lldp.py \ No newline at end of file diff --git a/plugins/modules/vyos_lldp.py b/plugins/modules/vyos_lldp.py new file mode 100644 index 0000000..aa7a316 --- /dev/null +++ b/plugins/modules/vyos_lldp.py @@ -0,0 +1,145 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2017, Ansible by Red Hat, inc +# +# This file is part of Ansible by Red Hat +# +# 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 + + +ANSIBLE_METADATA = { + "metadata_version": "1.1", + "status": ["deprecated"], + "supported_by": "network", +} + + +DOCUMENTATION = """module: vyos_lldp +author: Ricardo Carrillo Cruz (@rcarrillocruz) +short_description: Manage LLDP configuration on VyOS network devices +description: +- This module provides declarative management of LLDP service on VyOS network devices. +deprecated: + removed_in: '2.13' + alternative: vyos_lldp_global + why: Updated modules released with more functionality. +notes: +- Tested against VYOS 1.1.7 +options: + interfaces: + description: + - Name of the interfaces. + type: list + state: + description: + - State of the link aggregation group. + default: present + choices: + - present + - absent + - enabled + - disabled + type: str +extends_documentation_fragment: +- vyos.vyos.vyos +""" + +EXAMPLES = """ +- name: Enable LLDP service + vyos_lldp: + state: present + +- name: Disable LLDP service + vyos_lldp: + state: absent +""" + +RETURN = """ +commands: + description: The list of configuration mode commands to send to the device + returned: always, except for the platforms that use Netconf transport to manage the device. + type: list + sample: + - set service lldp +""" +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + get_config, + load_config, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + vyos_argument_spec, +) + + +def has_lldp(module): + config = get_config(module).splitlines() + + if "set service 'lldp'" in config or "set service lldp" in config: + return True + else: + return False + + +def main(): + """ main entry point for module execution + """ + argument_spec = dict( + interfaces=dict(type="list"), + state=dict( + default="present", + choices=["present", "absent", "enabled", "disabled"], + ), + ) + + argument_spec.update(vyos_argument_spec) + + module = AnsibleModule( + argument_spec=argument_spec, supports_check_mode=True + ) + + warnings = list() + + result = {"changed": False} + + if warnings: + result["warnings"] = warnings + + HAS_LLDP = has_lldp(module) + + commands = [] + + if module.params["state"] == "absent" and HAS_LLDP: + commands.append("delete service lldp") + elif module.params["state"] == "present" and not HAS_LLDP: + commands.append("set service lldp") + + result["commands"] = commands + + if commands: + commit = not module.check_mode + load_config(module, commands, commit=commit) + result["changed"] = True + + module.exit_json(**result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/vyos_lldp_global.py b/plugins/modules/vyos_lldp_global.py index 55b1a1a..08eb113 100644 --- a/plugins/modules/vyos_lldp_global.py +++ b/plugins/modules/vyos_lldp_global.py @@ -1,333 +1,332 @@ #!/usr/bin/python # -*- 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) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The module file for vyos_lldp_global """ from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_lldp_global -version_added: 2.9 -short_description: Manage link layer discovery protocol (LLDP) attributes on VyOS devices.. -description: This module manages link layer discovery protocol (LLDP) attributes on VyOS devices. +DOCUMENTATION = """module: vyos_lldp_global +short_description: Manage link layer discovery protocol (LLDP) attributes on VyOS + devices.. +description: This module manages link layer discovery protocol (LLDP) attributes on + VyOS devices. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). author: - - Rohit Thakur (@rohitthakur2590) +- Rohit Thakur (@rohitthakur2590) options: config: description: The provided link layer discovery protocol (LLDP) configuration. type: dict suboptions: enable: description: - - This argument is a boolean value to enable or disable LLDP. + - This argument is a boolean value to enable or disable LLDP. type: bool address: description: - - This argument defines management-address. + - This argument defines management-address. type: str snmp: description: - - This argument enable the SNMP queries to LLDP database. + - This argument enable the SNMP queries to LLDP database. type: str legacy_protocols: description: - - List of the supported legacy protocols. + - List of the supported legacy protocols. type: list choices: - - cdp - - edp - - fdp - - sonmp + - cdp + - edp + - fdp + - sonmp state: description: - - The state of the configuration after module completion. + - The state of the configuration after module completion. type: str choices: - merged - replaced - deleted default: merged """ EXAMPLES = """ # Using merged # # Before state: # ------------- # # vyos@vyos:~$ show configuration commands|grep lldp # vyos@vyos:~$ # - name: Merge provided configuration with device configuration vyos_lldp_global: config: legacy_protocols: - 'fdp' - 'cdp' snmp: 'enable' address: 192.0.2.11 state: merged # # # ------------------------ # Module Execution Results # ------------------------ # # "before": [] # # "commands": [ # "set service lldp legacy-protocols fdp", # "set service lldp legacy-protocols cdp", # "set service lldp snmp enable", # "set service lldp management-address '192.0.2.11'" # ] # # "after": [ # { # "snmp": "enable" # }, # { # "address": "192.0.2.11" # }, # { # "legacy_protocols": [ # "cdp", # "fdp" # ] # } # { # "enable": true # } # ] # # After state: # ------------- # # set service lldp legacy-protocols cdp # set service lldp legacy-protocols fdp # set service lldp management-address '192.0.2.11' # set service lldp snmp enable # Using replaced # # Before state: # ------------- # # vyos@vyos:~$ show configuration commands | grep lldp # set service lldp legacy-protocols cdp # set service lldp legacy-protocols fdp # set service lldp management-address '192.0.2.11' # set service lldp snmp enable # - name: Replace device configurations with provided configurations vyos_lldp_global: config: legacy_protocols: - 'edp' - 'sonmp' - 'cdp' address: 192.0.2.14 state: replaced # # # ------------------------ # Module Execution Results # ------------------------ # # # "before": [ # { # "snmp": "enable" # }, # { # "address": "192.0.2.11" # }, # { # "legacy_protocols": [ # "cdp", # "fdp" # ] # } # { # "enable": true # } # ] # "commands": [ # "delete service lldp snmp", # "delete service lldp legacy-protocols fdp", # "set service lldp management-address '192.0.2.14'", # "set service lldp legacy-protocols edp", # "set service lldp legacy-protocols sonmp" # ] # # "after": [ # { # "address": "192.0.2.14" # }, # { # "legacy_protocols": [ # "cdp", # "edp", # "sonmp" # ] # } # { # "enable": true # } # ] # # After state: # ------------- # # vyos@vyos:~$ show configuration commands|grep lldp # set service lldp legacy-protocols cdp # set service lldp legacy-protocols edp # set service lldp legacy-protocols sonmp # set service lldp management-address '192.0.2.14' # Using deleted # # Before state # ------------- # vyos@vyos:~$ show configuration commands|grep lldp # set service lldp legacy-protocols cdp # set service lldp legacy-protocols edp # set service lldp legacy-protocols sonmp # set service lldp management-address '192.0.2.14' # - name: Delete attributes of given lldp service (This won't delete the LLDP service itself) vyos_lldp_global: config: state: deleted # # # ------------------------ # Module Execution Results # ------------------------ # # "before": [ # { # "address": "192.0.2.14" # }, # { # "legacy_protocols": [ # "cdp", # "edp", # "sonmp" # ] # } # { # "enable": true # } # ] # # "commands": [ # "delete service lldp management-address", # "delete service lldp legacy-protocols" # ] # # "after": [ # { # "enable": true # } # ] # # After state # ------------ # vyos@vyos:~$ show configuration commands | grep lldp # set service lldp """ RETURN = """ before: description: The configuration as structured data prior to module invocation. returned: always type: list sample: > The configuration returned will always be in the same format of the parameters above. after: description: The configuration as structured data after module completion. returned: when changed type: list sample: > The configuration returned will always be in the same format of the parameters above. commands: description: The set of commands pushed to the remote device. returned: always type: list sample: - set service lldp legacy-protocols sonmp - set service lldp management-address '192.0.2.14' """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.lldp_global.lldp_global import ( Lldp_globalArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.lldp_global.lldp_global import ( Lldp_global, ) def main(): """ Main entry point for module execution :returns: the result form module invocation """ required_if = [ ("state", "merged", ("config",)), ("state", "replaced", ("config",)), ] module = AnsibleModule( argument_spec=Lldp_globalArgs.argument_spec, required_if=required_if, supports_check_mode=True, ) result = Lldp_global(module).execute_module() module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_lldp_interface.py b/plugins/modules/vyos_lldp_interface.py deleted file mode 120000 index 7847a58..0000000 --- a/plugins/modules/vyos_lldp_interface.py +++ /dev/null @@ -1 +0,0 @@ -_vyos_lldp_interface.py \ No newline at end of file diff --git a/plugins/modules/vyos_lldp_interface.py b/plugins/modules/vyos_lldp_interface.py new file mode 100644 index 0000000..402facf --- /dev/null +++ b/plugins/modules/vyos_lldp_interface.py @@ -0,0 +1,264 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +# (c) 2017, Ansible by Red Hat, inc +# +# This file is part of Ansible by Red Hat +# +# 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 . +# + + +ANSIBLE_METADATA = { + "metadata_version": "1.1", + "status": ["deprecated"], + "supported_by": "network", +} + + +DOCUMENTATION = """module: vyos_lldp_interface +author: Ricardo Carrillo Cruz (@rcarrillocruz) +short_description: Manage LLDP interfaces configuration on VyOS network devices +description: +- This module provides declarative management of LLDP interfaces configuration on + VyOS network devices. +deprecated: + removed_in: '2.13' + alternative: vyos_lldp_interfaces + why: Updated modules released with more functionality. +notes: +- Tested against VYOS 1.1.7 +options: + name: + description: + - Name of the interface LLDP should be configured on. + type: str + aggregate: + description: List of interfaces LLDP should be configured on. + type: list + state: + description: + - State of the LLDP configuration. + default: present + choices: + - present + - absent + - enabled + - disabled + type: str +extends_documentation_fragment: +- vyos.vyos.vyos +""" + +EXAMPLES = """ +- name: Enable LLDP on eth1 + net_lldp_interface: + state: present + +- name: Enable LLDP on specific interfaces + net_lldp_interface: + interfaces: + - eth1 + - eth2 + state: present + +- name: Disable LLDP globally + net_lldp_interface: + state: disabled + +- name: Create aggregate of LLDP interface configurations + vyos_lldp_interface: + aggregate: + - name: eth1 + - name: eth2 + state: present + +- name: Delete aggregate of LLDP interface configurations + vyos_lldp_interface: + aggregate: + - name: eth1 + - name: eth2 + state: absent +""" + +RETURN = """ +commands: + description: The list of configuration mode commands to send to the device + returned: always, except for the platforms that use Netconf transport to manage the device. + type: list + sample: + - set service lldp eth1 + - set service lldp eth2 disable +""" + + +from copy import deepcopy + +from ansible.module_utils.basic import AnsibleModule +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + remove_default_spec, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + get_config, + load_config, +) +from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( + vyos_argument_spec, +) + + +def search_obj_in_list(name, lst): + for o in lst: + if o["name"] == name: + return o + + return None + + +def map_obj_to_commands(updates, module): + commands = list() + want, have = updates + + for w in want: + name = w["name"] + state = w["state"] + + obj_in_have = search_obj_in_list(name, have) + + if state == "absent" and obj_in_have: + commands.append("delete service lldp interface " + name) + elif state in ("present", "enabled"): + if not obj_in_have: + commands.append("set service lldp interface " + name) + elif ( + obj_in_have + and obj_in_have["state"] == "disabled" + and state == "enabled" + ): + commands.append( + "delete service lldp interface " + name + " disable" + ) + elif state == "disabled": + if not obj_in_have: + commands.append("set service lldp interface " + name) + commands.append( + "set service lldp interface " + name + " disable" + ) + elif obj_in_have and obj_in_have["state"] != "disabled": + commands.append( + "set service lldp interface " + name + " disable" + ) + + return commands + + +def map_config_to_obj(module): + obj = [] + config = get_config(module).splitlines() + + output = [c for c in config if c.startswith("set service lldp interface")] + + for i in output: + splitted_line = i.split() + + if len(splitted_line) > 5: + new_obj = {"name": splitted_line[4]} + + if splitted_line[5] == "'disable'": + new_obj["state"] = "disabled" + else: + new_obj = {"name": splitted_line[4][1:-1]} + new_obj["state"] = "present" + + obj.append(new_obj) + + return obj + + +def map_params_to_obj(module): + obj = [] + + aggregate = module.params.get("aggregate") + if aggregate: + for item in aggregate: + for key in item: + if item.get(key) is None: + item[key] = module.params[key] + + obj.append(item.copy()) + else: + obj.append( + {"name": module.params["name"], "state": module.params["state"]} + ) + + return obj + + +def main(): + """ main entry point for module execution + """ + element_spec = dict( + name=dict(), + state=dict( + default="present", + choices=["present", "absent", "enabled", "disabled"], + ), + ) + + aggregate_spec = deepcopy(element_spec) + aggregate_spec["name"] = dict(required=True) + + # remove default in aggregate spec, to handle common arguments + remove_default_spec(aggregate_spec) + + argument_spec = dict( + aggregate=dict(type="list", elements="dict", options=aggregate_spec), + ) + + argument_spec.update(element_spec) + argument_spec.update(vyos_argument_spec) + + required_one_of = [["name", "aggregate"]] + mutually_exclusive = [["name", "aggregate"]] + + module = AnsibleModule( + argument_spec=argument_spec, + required_one_of=required_one_of, + mutually_exclusive=mutually_exclusive, + supports_check_mode=True, + ) + + warnings = list() + + result = {"changed": False} + + if warnings: + result["warnings"] = warnings + + want = map_params_to_obj(module) + have = map_config_to_obj(module) + + commands = map_obj_to_commands((want, have), module) + result["commands"] = commands + + if commands: + commit = not module.check_mode + load_config(module, commands, commit=commit) + result["changed"] = True + + module.exit_json(**result) + + +if __name__ == "__main__": + main() diff --git a/plugins/modules/vyos_lldp_interfaces.py b/plugins/modules/vyos_lldp_interfaces.py index 70ceed8..8fe572b 100644 --- a/plugins/modules/vyos_lldp_interfaces.py +++ b/plugins/modules/vyos_lldp_interfaces.py @@ -1,517 +1,513 @@ #!/usr/bin/python # -*- 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) ############################################# # WARNING # ############################################# # # This file is auto generated by the resource # module builder playbook. # # Do not edit this file manually. # # Changes to this file will be over written # by the resource module builder. # # Changes should be made in the model used to # generate this file or in the resource module # builder template. # ############################################# """ The module file for vyos_lldp_interfaces """ from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_lldp_interfaces -version_added: 2.9 +DOCUMENTATION = """module: vyos_lldp_interfaces short_description: Manages attributes of lldp interfaces on VyOS devices. description: This module manages attributes of lldp interfaces on VyOS network devices. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). author: - - Rohit Thakur (@rohitthakur2590) +- Rohit Thakur (@rohitthakur2590) options: config: description: A list of lldp interfaces configurations. type: list suboptions: name: description: - - Name of the lldp interface. + - Name of the lldp interface. type: str - required: True + required: true enable: description: - - to disable lldp on the interface. + - to disable lldp on the interface. type: bool - default: True + default: true location: description: - - LLDP-MED location data. + - LLDP-MED location data. type: dict suboptions: civic_based: description: - - Civic-based location data. + - Civic-based location data. type: dict suboptions: ca_info: - description: LLDP-MED address info - type: list - suboptions: - ca_type: - description: LLDP-MED Civic Address type. - type: int - required: True - ca_value: - description: LLDP-MED Civic Address value. - type: str - required: True + description: LLDP-MED address info + type: list + suboptions: + ca_type: + description: LLDP-MED Civic Address type. + type: int + required: true + ca_value: + description: LLDP-MED Civic Address value. + type: str + required: true country_code: description: Country Code type: str - required: True + required: true coordinate_based: description: - - Coordinate-based location. + - Coordinate-based location. type: dict suboptions: altitude: description: Altitude in meters. type: int datum: description: Coordinate datum type. type: str choices: - - WGS84 - - NAD83 - - MLLW + - WGS84 + - NAD83 + - MLLW latitude: description: Latitude. type: str - required: True + required: true longitude: description: Longitude. type: str - required: True + required: true elin: description: Emergency Call Service ELIN number (between 10-25 numbers). type: str state: description: - - The state of the configuration after module completion. + - The state of the configuration after module completion. type: str choices: - merged - replaced - overridden - deleted default: merged - """ EXAMPLES = """ # Using merged # # Before state: # ------------- # # vyos@vyos:~$ show configuration commands | grep lldp # - name: Merge provided configuration with device configuration vyos_lldp_interfaces: config: - name: 'eth1' location: civic_based: country_code: 'US' ca_info: - ca_type: 0 ca_value: 'ENGLISH' - name: 'eth2' location: coordinate_based: altitude: 2200 datum: 'WGS84' longitude: '222.267255W' latitude: '33.524449N' state: merged # # # ------------------------- # Module Execution Result # ------------------------- # # before": [] # # "commands": [ # "set service lldp interface eth1 location civic-based country-code 'US'", # "set service lldp interface eth1 location civic-based ca-type 0 ca-value 'ENGLISH'", # "set service lldp interface eth1", # "set service lldp interface eth2 location coordinate-based latitude '33.524449N'", # "set service lldp interface eth2 location coordinate-based altitude '2200'", # "set service lldp interface eth2 location coordinate-based datum 'WGS84'", # "set service lldp interface eth2 location coordinate-based longitude '222.267255W'", # "set service lldp interface eth2 location coordinate-based latitude '33.524449N'", # "set service lldp interface eth2 location coordinate-based altitude '2200'", # "set service lldp interface eth2 location coordinate-based datum 'WGS84'", # "set service lldp interface eth2 location coordinate-based longitude '222.267255W'", # "set service lldp interface eth2" # # "after": [ # { # "location": { # "coordinate_based": { # "altitude": 2200, # "datum": "WGS84", # "latitude": "33.524449N", # "longitude": "222.267255W" # } # }, # "name": "eth2" # }, # { # "location": { # "civic_based": { # "ca_info": [ # { # "ca_type": 0, # "ca_value": "ENGLISH" # } # ], # "country_code": "US" # } # }, # "name": "eth1" # } # ], # # After state: # ------------- # # vyos@vyos:~$ show configuration commands | grep lldp # set service lldp interface eth1 location civic-based ca-type 0 ca-value 'ENGLISH' # set service lldp interface eth1 location civic-based country-code 'US' # set service lldp interface eth2 location coordinate-based altitude '2200' # set service lldp interface eth2 location coordinate-based datum 'WGS84' # set service lldp interface eth2 location coordinate-based latitude '33.524449N' # set service lldp interface eth2 location coordinate-based longitude '222.267255W' # Using replaced # # Before state: # ------------- # # vyos@vyos:~$ show configuration commands | grep lldp # set service lldp interface eth1 location civic-based ca-type 0 ca-value 'ENGLISH' # set service lldp interface eth1 location civic-based country-code 'US' # set service lldp interface eth2 location coordinate-based altitude '2200' # set service lldp interface eth2 location coordinate-based datum 'WGS84' # set service lldp interface eth2 location coordinate-based latitude '33.524449N' # set service lldp interface eth2 location coordinate-based longitude '222.267255W' # - name: Replace device configurations of listed LLDP interfaces with provided configurations vyos_lldp_interfaces: config: - name: 'eth2' location: civic_based: country_code: 'US' ca_info: - ca_type: 0 ca_value: 'ENGLISH' - name: 'eth1' location: coordinate_based: altitude: 2200 datum: 'WGS84' longitude: '222.267255W' latitude: '33.524449N' state: replaced # # # ------------------------- # Module Execution Result # ------------------------- # # "before": [ # { # "location": { # "coordinate_based": { # "altitude": 2200, # "datum": "WGS84", # "latitude": "33.524449N", # "longitude": "222.267255W" # } # }, # "name": "eth2" # }, # { # "location": { # "civic_based": { # "ca_info": [ # { # "ca_type": 0, # "ca_value": "ENGLISH" # } # ], # "country_code": "US" # } # }, # "name": "eth1" # } # ] # # "commands": [ # "delete service lldp interface eth2 location", # "set service lldp interface eth2 'disable'", # "set service lldp interface eth2 location civic-based country-code 'US'", # "set service lldp interface eth2 location civic-based ca-type 0 ca-value 'ENGLISH'", # "delete service lldp interface eth1 location", # "set service lldp interface eth1 'disable'", # "set service lldp interface eth1 location coordinate-based latitude '33.524449N'", # "set service lldp interface eth1 location coordinate-based altitude '2200'", # "set service lldp interface eth1 location coordinate-based datum 'WGS84'", # "set service lldp interface eth1 location coordinate-based longitude '222.267255W'" # ] # # "after": [ # { # "location": { # "civic_based": { # "ca_info": [ # { # "ca_type": 0, # "ca_value": "ENGLISH" # } # ], # "country_code": "US" # } # }, # "name": "eth2" # }, # { # "location": { # "coordinate_based": { # "altitude": 2200, # "datum": "WGS84", # "latitude": "33.524449N", # "longitude": "222.267255W" # } # }, # "name": "eth1" # } # ] # # After state: # ------------- # # vyos@vyos:~$ show configuration commands | grep lldp # set service lldp interface eth1 'disable' # set service lldp interface eth1 location coordinate-based altitude '2200' # set service lldp interface eth1 location coordinate-based datum 'WGS84' # set service lldp interface eth1 location coordinate-based latitude '33.524449N' # set service lldp interface eth1 location coordinate-based longitude '222.267255W' # set service lldp interface eth2 'disable' # set service lldp interface eth2 location civic-based ca-type 0 ca-value 'ENGLISH' # set service lldp interface eth2 location civic-based country-code 'US' # Using overridden # # Before state # -------------- # # vyos@vyos:~$ show configuration commands | grep lldp # set service lldp interface eth1 'disable' # set service lldp interface eth1 location coordinate-based altitude '2200' # set service lldp interface eth1 location coordinate-based datum 'WGS84' # set service lldp interface eth1 location coordinate-based latitude '33.524449N' # set service lldp interface eth1 location coordinate-based longitude '222.267255W' # set service lldp interface eth2 'disable' # set service lldp interface eth2 location civic-based ca-type 0 ca-value 'ENGLISH' # set service lldp interface eth2 location civic-based country-code 'US' # - name: Overrides all device configuration with provided configuration vyos_lag_interfaces: config: - name: 'eth2' location: elin: 0000000911 state: overridden # # # ------------------------- # Module Execution Result # ------------------------- # # "before": [ # { # "enable": false, # "location": { # "civic_based": { # "ca_info": [ # { # "ca_type": 0, # "ca_value": "ENGLISH" # } # ], # "country_code": "US" # } # }, # "name": "eth2" # }, # { # "enable": false, # "location": { # "coordinate_based": { # "altitude": 2200, # "datum": "WGS84", # "latitude": "33.524449N", # "longitude": "222.267255W" # } # }, # "name": "eth1" # } # ] # # "commands": [ # "delete service lldp interface eth2 location", # "delete service lldp interface eth2 disable", # "set service lldp interface eth2 location elin 0000000911" # # # "after": [ # { # "location": { # "elin": 0000000911 # }, # "name": "eth2" # } # ] # # # After state # ------------ # # vyos@vyos# run show configuration commands | grep lldp # set service lldp interface eth2 location elin '0000000911' # Using deleted # # Before state # ------------- # # vyos@vyos# run show configuration commands | grep lldp # set service lldp interface eth2 location elin '0000000911' # - name: Delete lldp interface attributes of given interfaces. vyos_lag_interfaces: config: - name: 'eth2' state: deleted # # # ------------------------ # Module Execution Results # ------------------------ # "before": [ { "location": { "elin": 0000000911 }, "name": "eth2" } ] # "commands": [ # "commands": [ # "delete service lldp interface eth2" # ] # # "after": [] # After state # ------------ # vyos@vyos# run show configuration commands | grep lldp # set service 'lldp' """ RETURN = """ before: description: The configuration as structured data prior to module invocation. returned: always type: list sample: > The configuration returned will always be in the same format of the parameters above. after: description: The configuration as structured data after module completion. returned: when changed type: list sample: > The configuration returned will always be in the same format of the parameters above. commands: description: The set of commands pushed to the remote device. returned: always type: list sample: - "set service lldp interface eth2 'disable'" - "delete service lldp interface eth1 location" """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.argspec.lldp_interfaces.lldp_interfaces import ( Lldp_interfacesArgs, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.config.lldp_interfaces.lldp_interfaces import ( Lldp_interfaces, ) def main(): """ Main entry point for module execution :returns: the result form module invocation """ required_if = [ ("state", "merged", ("config",)), ("state", "replaced", ("config",)), ("state", "overridden", ("config",)), ] module = AnsibleModule( argument_spec=Lldp_interfacesArgs.argument_spec, required_if=required_if, supports_check_mode=True, ) result = Lldp_interfaces(module).execute_module() module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_logging.py b/plugins/modules/vyos_logging.py index 6c2f9f7..9f81eb9 100644 --- a/plugins/modules/vyos_logging.py +++ b/plugins/modules/vyos_logging.py @@ -1,295 +1,300 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # 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 . # ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "network", } -DOCUMENTATION = """ ---- -module: vyos_logging -version_added: "2.4" -author: "Trishna Guha (@trishnaguha)" +DOCUMENTATION = """module: vyos_logging +author: Trishna Guha (@trishnaguha) short_description: Manage logging on network devices description: - - This module provides declarative management of logging - on Vyatta Vyos devices. +- This module provides declarative management of logging on Vyatta Vyos devices. notes: - - Tested against VyOS 1.1.8 (helium). - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +- Tested against VyOS 1.1.8 (helium). +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). options: dest: description: - - Destination of the logs. - choices: ['console', 'file', 'global', 'host', 'user'] + - Destination of the logs. + choices: + - console + - file + - global + - host + - user name: description: - - If value of C(dest) is I(file) it indicates file-name, - for I(user) it indicates username and for I(host) indicates - the host name to be notified. + - If value of C(dest) is I(file) it indicates file-name, for I(user) it indicates + username and for I(host) indicates the host name to be notified. facility: description: - - Set logging facility. + - Set logging facility. level: description: - - Set logging severity levels. + - Set logging severity levels. aggregate: description: List of logging definitions. state: description: - - State of the logging configuration. + - State of the logging configuration. default: present - choices: ['present', 'absent'] -extends_documentation_fragment: vyos + choices: + - present + - absent +extends_documentation_fragment: +- vyos.vyos.vyos """ EXAMPLES = """ - name: configure console logging vyos_logging: dest: console facility: all level: crit - name: remove console logging configuration vyos_logging: dest: console state: absent - name: configure file logging vyos_logging: dest: file name: test facility: local3 level: err - name: Add logging aggregate vyos_logging: aggregate: - { dest: file, name: test1, facility: all, level: info } - { dest: file, name: test2, facility: news, level: debug } state: present - name: Remove logging aggregate vyos_logging: aggregate: - { dest: console, facility: all, level: info } - { dest: console, facility: daemon, level: warning } - { dest: file, name: test2, facility: news, level: debug } state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - set system syslog global facility all level notice """ import re from copy import deepcopy from ansible.module_utils.basic import AnsibleModule -from ansible.module_utils.network.common.utils import remove_default_spec +from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import ( + remove_default_spec, +) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( get_config, load_config, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( vyos_argument_spec, ) def spec_to_commands(updates, module): commands = list() want, have = updates for w in want: dest = w["dest"] name = w["name"] facility = w["facility"] level = w["level"] state = w["state"] del w["state"] if state == "absent" and w in have: if w["name"]: commands.append( "delete system syslog {0} {1} facility {2} level {3}".format( dest, name, facility, level ) ) else: commands.append( "delete system syslog {0} facility {1} level {2}".format( dest, facility, level ) ) elif state == "present" and w not in have: if w["name"]: commands.append( "set system syslog {0} {1} facility {2} level {3}".format( dest, name, facility, level ) ) else: commands.append( "set system syslog {0} facility {1} level {2}".format( dest, facility, level ) ) return commands def config_to_dict(module): data = get_config(module) obj = [] for line in data.split("\n"): if line.startswith("set system syslog"): match = re.search(r"set system syslog (\S+)", line, re.M) dest = match.group(1) if dest == "host": match = re.search(r"host (\S+)", line, re.M) name = match.group(1) elif dest == "file": match = re.search(r"file (\S+)", line, re.M) name = match.group(1) elif dest == "user": match = re.search(r"user (\S+)", line, re.M) name = match.group(1) else: name = None if "facility" in line: match = re.search(r"facility (\S+)", line, re.M) facility = match.group(1) if "level" in line: match = re.search(r"level (\S+)", line, re.M) level = match.group(1).strip("'") obj.append( { "dest": dest, "name": name, "facility": facility, "level": level, } ) return obj def map_params_to_obj(module, required_if=None): obj = [] aggregate = module.params.get("aggregate") if aggregate: for item in aggregate: for key in item: if item.get(key) is None: item[key] = module.params[key] module._check_required_if(required_if, item) obj.append(item.copy()) else: if module.params["dest"] not in ("host", "file", "user"): module.params["name"] = None obj.append( { "dest": module.params["dest"], "name": module.params["name"], "facility": module.params["facility"], "level": module.params["level"], "state": module.params["state"], } ) return obj def main(): """ main entry point for module execution """ element_spec = dict( dest=dict( type="str", choices=["console", "file", "global", "host", "user"] ), name=dict(type="str"), facility=dict(type="str"), level=dict(type="str"), state=dict(default="present", choices=["present", "absent"]), ) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( - aggregate=dict(type="list", elements="dict", options=aggregate_spec) + aggregate=dict(type="list", elements="dict", options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(vyos_argument_spec) required_if = [ ("dest", "host", ["name", "facility", "level"]), ("dest", "file", ["name", "facility", "level"]), ("dest", "user", ["name", "facility", "level"]), ("dest", "console", ["facility", "level"]), ("dest", "global", ["facility", "level"]), ] module = AnsibleModule( argument_spec=argument_spec, required_if=required_if, supports_check_mode=True, ) warnings = list() result = {"changed": False} if warnings: result["warnings"] = warnings want = map_params_to_obj(module, required_if=required_if) have = config_to_dict(module) commands = spec_to_commands((want, have), module) result["commands"] = commands if commands: commit = not module.check_mode load_config(module, commands, commit=commit) result["changed"] = True module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_ping.py b/plugins/modules/vyos_ping.py index 8271049..3d5a903 100644 --- a/plugins/modules/vyos_ping.py +++ b/plugins/modules/vyos_ping.py @@ -1,262 +1,262 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Ansible by Red Hat, inc # # This file is part of Ansible by Red Hat # # 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 ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } -DOCUMENTATION = """ ---- -module: vyos_ping +DOCUMENTATION = """module: vyos_ping short_description: Tests reachability using ping from VyOS network devices description: - - Tests reachability using ping from a VyOS device to a remote destination. - - Tested against VyOS 1.1.8 (helium) - - For a general purpose network module, see the M(net_ping) module. - - For Windows targets, use the M(win_ping) module instead. - - For targets running Python, use the M(ping) module instead. +- Tests reachability using ping from a VyOS device to a remote destination. +- Tested against VyOS 1.1.8 (helium) +- For a general purpose network module, see the M(net_ping) module. +- For Windows targets, use the M(win_ping) module instead. +- For targets running Python, use the M(ping) module instead. author: - - Nilashish Chakraborty (@NilashishC) -version_added: '2.8' +- Nilashish Chakraborty (@NilashishC) options: dest: description: - - The IP Address or hostname (resolvable by the device) of the remote node. + - The IP Address or hostname (resolvable by the device) of the remote node. required: true count: description: - - Number of packets to send to check reachability. + - Number of packets to send to check reachability. type: int default: 5 source: description: - - The source interface or IP Address to use while sending the ping packet(s). + - The source interface or IP Address to use while sending the ping packet(s). ttl: description: - - The time-to-live value for the ICMP packet(s). + - The time-to-live value for the ICMP packet(s). type: int size: description: - - Determines the size (in bytes) of the ping packet(s). + - Determines the size (in bytes) of the ping packet(s). type: int interval: description: - - Determines the interval (in seconds) between consecutive pings. + - Determines the interval (in seconds) between consecutive pings. type: int state: description: - - Determines if the expected result is success or fail. - choices: [ absent, present ] + - Determines if the expected result is success or fail. + choices: + - absent + - present default: present notes: - - Tested against VyOS 1.1.8 (helium). - - For a general purpose network module, see the M(net_ping) module. - - For Windows targets, use the M(win_ping) module instead. - - For targets running Python, use the M(ping) module instead. - - This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). -extends_documentation_fragment: vyos +- Tested against VyOS 1.1.8 (helium). +- For a general purpose network module, see the M(net_ping) module. +- For Windows targets, use the M(win_ping) module instead. +- For targets running Python, use the M(ping) module instead. +- This module works with connection C(network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). +extends_documentation_fragment: +- vyos.vyos.vyos """ EXAMPLES = """ - name: Test reachability to 10.10.10.10 vyos_ping: dest: 10.10.10.10 - name: Test reachability to 10.20.20.20 using source and ttl set vyos_ping: dest: 10.20.20.20 source: eth0 ttl: 128 - name: Test unreachability to 10.30.30.30 using interval vyos_ping: dest: 10.30.30.30 interval: 3 state: absent - name: Test reachability to 10.40.40.40 setting count and source vyos_ping: dest: 10.40.40.40 source: eth1 count: 20 size: 512 """ RETURN = """ commands: description: List of commands sent. returned: always type: list sample: ["ping 10.8.38.44 count 10 interface eth0 ttl 128"] packet_loss: description: Percentage of packets lost. returned: always type: str sample: "0%" packets_rx: description: Packets successfully received. returned: always type: int sample: 20 packets_tx: description: Packets successfully transmitted. returned: always type: int sample: 20 rtt: description: The round trip time (RTT) stats. returned: when ping succeeds type: dict sample: {"avg": 2, "max": 8, "min": 1, "mdev": 24} """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( run_commands, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( vyos_argument_spec, ) import re def main(): """ main entry point for module execution """ argument_spec = dict( count=dict(type="int", default=5), dest=dict(type="str", required=True), source=dict(type="str"), ttl=dict(type="int"), size=dict(type="int"), interval=dict(type="int"), state=dict( type="str", choices=["absent", "present"], default="present" ), ) argument_spec.update(vyos_argument_spec) module = AnsibleModule(argument_spec=argument_spec) count = module.params["count"] dest = module.params["dest"] source = module.params["source"] size = module.params["size"] ttl = module.params["ttl"] interval = module.params["interval"] warnings = list() results = {} if warnings: results["warnings"] = warnings results["commands"] = [ build_ping(dest, count, size, interval, source, ttl) ] ping_results = run_commands(module, commands=results["commands"]) ping_results_list = ping_results[0].split("\n") rtt_info, rate_info = None, None for line in ping_results_list: if line.startswith("rtt"): rtt_info = line if line.startswith("%s packets transmitted" % count): rate_info = line if rtt_info: rtt = parse_rtt(rtt_info) for k, v in rtt.items(): if rtt[k] is not None: rtt[k] = int(v) results["rtt"] = rtt pkt_loss, rx, tx = parse_rate(rate_info) results["packet_loss"] = str(pkt_loss) + "%" results["packets_rx"] = int(rx) results["packets_tx"] = int(tx) validate_results(module, pkt_loss, results) module.exit_json(**results) def build_ping(dest, count, size=None, interval=None, source=None, ttl=None): cmd = "ping {0} count {1}".format(dest, str(count)) if source: cmd += " interface {0}".format(source) if ttl: cmd += " ttl {0}".format(str(ttl)) if size: cmd += " size {0}".format(str(size)) if interval: cmd += " interval {0}".format(str(interval)) return cmd def parse_rate(rate_info): rate_re = re.compile( r"(?P\d+) (?:\w+) (?:\w+), (?P\d+) (?:\w+), (?P\d+)% (?:\w+) (?:\w+), (?:\w+) (?P