diff --git a/changelogs/fragments/t9324_to_text_imports_fix.yml b/changelogs/fragments/t9324_to_text_imports_fix.yml new file mode 100644 index 00000000..4f13ef57 --- /dev/null +++ b/changelogs/fragments/t9324_to_text_imports_fix.yml @@ -0,0 +1,3 @@ +--- +trivial: + - replace deprecated ansible.module_utils._text import to_text by ansible.module_utils.common.text.converters diff --git a/plugins/cliconf/vyos.py b/plugins/cliconf/vyos.py index e693f820..1a84573d 100644 --- a/plugins/cliconf/vyos.py +++ b/plugins/cliconf/vyos.py @@ -1,426 +1,426 @@ # (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 (@ansible-network) name: 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: 1.0.0 options: config_commands: description: - Specifies a list of commands that can make configuration changes to the target device. - When `ansible_network_single_user_mode` is enabled, if a command sent to the device is present in this list, the existing cache is invalidated. version_added: 2.0.0 type: list elements: str default: [] vars: - name: ansible_vyos_config_commands """ import json import re from ansible.errors import AnsibleConnectionFailure -from ansible.module_utils._text import to_text from ansible.module_utils.common._collections_compat import Mapping +from ansible.module_utils.common.text.converters import to_text from ansible.plugins.cliconf import CliconfBase 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_collections.vyos.vyos.plugins.cliconf_utils.vyosconf import VyosConf class Cliconf(CliconfBase): __rpc__ = CliconfBase.__rpc__ + [ "commit", "discard_changes", "get_diff", "run_commands", ] def __init__(self, *args, **kwargs): super(Cliconf, self).__init__(*args, **kwargs) self._device_info = {} def get_device_info(self): if not self._device_info: 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) if device_info["network_os_version"]: match = re.search(r"VyOS\s*(\d+\.\d+)", device_info["network_os_version"]) if match: device_info["network_os_major_version"] = match.group(1) match = re.search(r"(?:HW|Hardware) 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() self._device_info = device_info return self._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, diff=False, comment=None, confirm=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, confirm) 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, newline=True, output=None, 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, confirm=None): if confirm: if comment: command = 'commit-confirm {0} comment "{1}"'.format(confirm, comment) else: command = "commit-confirm {0}".format(confirm) self.send_command(command, "Proceed?", "\n") else: 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") first_line = next( ( stripped for stripped in (line.strip() for line in candidate.splitlines()) if stripped and not stripped.startswith("#") ), "", ) set_format = first_line.startswith("set") or first_line.startswith("delete") candidate_obj = NetworkConfig(indent=4, contents=candidate) if not set_format: config = [c.line for c in candidate_obj.items] commands = list() 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 = [ line.strip() for line in str(candidate).splitlines() if line.strip() and not line.lstrip().startswith("#") ] if diff_match == "none": diff["config_diff"] = list(candidate_commands) return diff if diff_match == "enforce": if running is None: raise ValueError( "diff_match=enforce requires a running configuration to diff against", ) enforce_candidate_lines = list(candidate_commands) if not enforce_candidate_lines: raise ValueError( "diff_match=enforce received an empty candidate (after stripping blank/" "comment lines); refusing to treat that as a desired end-state of " "'delete everything'. Provide 'set' commands describing the desired " "configuration.", ) for line in enforce_candidate_lines: tokens = line.strip().split() if tokens[0] != "set": raise ValueError( "diff_match=enforce treats the candidate as the complete desired " "configuration end-state and only supports 'set' commands; " "line does not start with 'set' (found: {0!r})".format( line.strip(), ), ) if len(VyosConf().parse_line(line)[1]) < 1: raise ValueError( "diff_match=enforce only supports complete 'set' commands with at least " "a path and a leaf; got: {0!r}".format(line.strip()), ) running_conf = VyosConf( [ line for line in running.splitlines() if line.strip() and not line.lstrip().startswith("#") ], ) candidate_conf = VyosConf(enforce_candidate_lines) diff["config_diff"] = running_conf.diff_commands_to(candidate_conf) for cmd in diff["config_diff"]: if re.match(r"^delete\s+service\s+ssh\b", cmd): raise ValueError( "diff_match=enforce refuses to generate 'delete service ssh ...' " "commands, since this could sever the management connection. " "Remove SSH configuration explicitly with a separate match=line " "or match=none task instead.", ) 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 re.match(rf"^{re.escape(item)}\b", entry) 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", "enforce", "none"], "diff_replace": [], "output": [], } def get_capabilities(self): result = super(Cliconf, self).get_capabilities() 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/module_utils/network/vyos/vyos.py b/plugins/module_utils/network/vyos/vyos.py index 4983221e..c710a7a8 100644 --- a/plugins/module_utils/network/vyos/vyos.py +++ b/plugins/module_utils/network/vyos/vyos.py @@ -1,143 +1,143 @@ # 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. # from __future__ import absolute_import, division, print_function __metaclass__ = type import json -from ansible.module_utils._text import to_text +from ansible.module_utils.common.text.converters import to_text from ansible.module_utils.connection import Connection, ConnectionError _DEVICE_CONFIGS = {} 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 is non-empty and module.params["match"] is "none", # return the cached device configurations. This avoids redundant calls # to the connection when no specific match criteria are provided. if _DEVICE_CONFIGS != {} and ( module.params["match"] is not None and module.params["match"] == "none" ): return to_text(_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 copy_file(module, source, destination, proto="scp"): """Copy a local file to the remote device over the existing network_cli SSH session, using netcommon's generic connection-level file transfer RPC (the same mechanism ansible.netcommon.net_put uses). Requires the device to have SCP/SFTP reachable over the same SSH session used for network_cli. Mirrors the calling convention of cisco.iosxr's module_utils copy_file(module, source, destination, proto), confirmed against cisco.iosxr's iosxr_config.py call site: copy_file(module, src, dst, "sftp"). """ connection = get_connection(module) try: timeout = connection.get_option("persistent_command_timeout") connection.copy_file( source=source, destination=destination, proto=proto, timeout=timeout, ) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) 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, confirm=None): connection = get_connection(module) try: response = connection.edit_config( candidate=commands, commit=commit, comment=comment, confirm=confirm, ) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors="surrogate_then_replace")) return response.get("diff") def get_os_version(module): connection = get_connection(module) if connection.get_device_info(): os_version = connection.get_device_info()["network_os_major_version"] return os_version diff --git a/plugins/modules/vyos_command.py b/plugins/modules/vyos_command.py index 5131dd88..5ba4baac 100644 --- a/plugins/modules/vyos_command.py +++ b/plugins/modules/vyos_command.py @@ -1,227 +1,228 @@ #!/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 . # from __future__ import absolute_import, division, print_function + __metaclass__ = type 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. version_added: 1.0.0 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. - If a command sent to the device requires answering a prompt, it is possible to pass a dict containing command, answer and prompt. Common answers are 'y' or "\\r" (carriage return, must be double quotes). Refer below examples. required: true type: list elements: raw 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. type: list elements: str 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. default: all type: str 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. - The commands are run once when I(retries) is set to C(0). default: 9 type: int 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. default: 1 type: int notes: - Tested against VyOS 1.3.8, 1.4.2, the upcoming 1.5, and the rolling release of spring 2025. - 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(ansible.netcommon.network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). """ EXAMPLES = """ - name: show configuration on ethernet devices eth0 and eth1 vyos.vyos.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.vyos.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.vyos.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.common.text.converters import to_text 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 ( to_lines, transform_commands, ) from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import run_commands 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, elements="raw"), wait_for=dict(type="list", aliases=["waitfor"], elements="str"), match=dict(default="all", choices=["all", "any"]), retries=dict(default=9, type="int"), interval=dict(default=1, type="int"), ) 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() conditionals = [] 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"] # Always run at least once, and then `retries` more times. for item in range(retries + 1): 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))}) module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_config.py b/plugins/modules/vyos_config.py index 53f8e043..88298dc2 100644 --- a/plugins/modules/vyos_config.py +++ b/plugins/modules/vyos_config.py @@ -1,665 +1,665 @@ #!/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 . # from __future__ import absolute_import, division, print_function __metaclass__ = type 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. version_added: 1.0.0 extends_documentation_fragment: - vyos.vyos.vyos notes: - Tested against VyOS 1.3.8, 1.4.2, the upcoming 1.5, and the rolling release of spring 2025. - This module works with connection C(ansible.netcommon.network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). - To ensure idempotency and correct diff the configuration lines in the relevant module options should be similar to how they appear if present in the running configuration on device including the indentation. - C(replace=config) currently has no way to scope its effect to part of the configuration; it always operates against the entire device configuration. There is no C(path) parameter to constrain it to a subtree. options: lines: description: - The ordered set of commands that should be configured in the section. The commands must be the exact same commands as found in the device running-config as found in the device running-config to ensure idempotency and correct diff. Be sure to note the configuration command syntax as some commands are automatically modified by the device config parser. - Not supported when C(replace) is set to C(config) -- see C(replace) below. type: list elements: str 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 configuration lines in the source file should be similar to how it will appear if present in the running-configuration of the device including indentation to ensure idempotency and correct diff. - When C(replace) is set to C(config), C(src) is required and must contain a complete configuration in hierarchical/bracket format -- the same format produced by C(show configuration) or found in C(/config/config.boot). Flat C(set)/C(delete) command format (as produced by C(show configuration commands)) is not accepted in that mode; VyOS's native C(load) command rejects it with a parse error. type: path 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. If the C(match) argument is set to C(enforce), the supplied C(lines) or C(src) are treated as the complete desired end-state of the configuration, rather than a set of deltas to apply. C(enforce) enforces only the top-level configuration sections present in the supplied candidate as complete end-states; existing configuration within those sections but not mentioned in the candidate is removed, so C(enforce) can generate C(delete) commands for configuration the candidate does not mention. Top-level sections the candidate does not reference at all are left completely untouched. C(enforce) is intended for candidates made up of C(set) commands only; supplying C(delete) lines alongside C(match=enforce) is not supported and will raise an error. - Ignored when C(replace) is set to C(config), since no line-level diff is computed in that mode. type: str default: line choices: - line - enforce - 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. 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 type: str confirm: description: - The C(confirm) argument will tell vyos to revert to the previous configuration if not explicitly confirmed after applying the new config. When set to C(automatic) this module will automatically confirm the configuration, if the current session remains working with the new config. When set to C(manual), this module does not issue the confirmation itself. - Defaults to C(automatic) when C(match) is set to C(enforce), since C(enforce) can generate C(delete) commands for configuration not mentioned in the candidate and a bad commit should self-revert rather than leave the device unreachable. Defaults to C(none) for all other C(match) values. type: str choices: - automatic - manual - none confirm_timeout: description: - Minutes to wait for confirmation before reverting the configuration. Does not apply when C(confirm) is set to C(none) . type: int default: 10 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 configuration lines in the option value should be similar to how it will appear if present in the running-configuration of the device including indentation to ensure idempotency and correct diff. - Ignored when C(replace) is set to C(config). type: str 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 C(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. suboptions: filename: description: - The filename to be used to store the backup configuration. If the filename is not given it will be generated based on the hostname, current time and date in format defined by _config.@ type: str 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. type: path type: dict replace: description: - Controls how the module applies configuration to the device. - When set to C(line) (default), the module computes a set/delete command diff and pushes only the changed lines -- this is the existing behavior, unchanged. - When set to C(config), the module uploads the full candidate configuration (C(src)) to the device and issues VyOS's native C(load) command in configuration mode, which replaces the running configuration wholesale with the candidate's exact contents. VyOS's own configuration engine performs the reconciliation, rather than the module computing per-line deltas. This mirrors the mechanism offered by C(cisco.iosxr.iosxr_config)'s C(replace=config). - C(replace=config) requires C(src) and does not accept C(lines) -- there is no way to convert flat set/delete commands into the hierarchical form C(load) requires without re-implementing VyOS's own config-tree builder. - As with C(src) in the default C(line) mode, the module does not validate the candidate's contents or format under C(replace=config) -- supplying a well-formed, complete configuration is the caller's responsibility. - C(replace=config) requires the device to accept file transfer (SCP) over the same C(network_cli) SSH session used for configuration commands. - C(replace=config) writes the candidate to a fixed path on the device (overwritten on each run, matching C(cisco.iosxr.iosxr_config)'s own C(replace=config) precedent). Running C(replace=config) concurrently against the same host is not supported. - Any configuration present on the device but omitted from the candidate will be removed, including management interfaces, SSH access, and login users if they are omitted. Always supply a complete configuration, never a partial one. - When capturing a candidate from the device's own output (for example via C(show configuration)) rather than from a trusted, separately maintained source, be aware that VyOS may return masked placeholder values (for example a run of literal asterisks) in place of local users' C(encrypted-password)/C(plaintext-password) values when queried through automation, even though the identical command returns the real value when typed interactively at a terminal. Pushing a masked capture back through C(replace=config) sends the literal placeholder as the new password value; VyOS's own commit-time validation is expected to reject an obviously malformed hash, but a masked value that happens to pass basic format validation could apply silently. Prefer sourcing C(replace=config) candidates from a trusted, version-controlled artifact rather than a live automated capture whenever the configuration contains local password-based users. - Even under C(check_mode), the candidate is written to a temporary file on the device so that VyOS's own C(compare) can produce an accurate preview diff. No C(commit) occurs in check mode. - When combined with C(backup=yes), the value of C(changed) reflects whether the backup file's content changed on the Ansible control node, not whether the device configuration changed -- this is existing behavior in the shared netcommon action plugin backing config-family modules across collections, not specific to C(replace=config). type: str default: line choices: - line - config allow_password_change: description: - The C(allow_password_change) argument specifies whether any configuration lines which would change a user's password should be filtered out. By default only plaintext password changes are allowed and any encrypted-password keys are filtered out. In order to allow all password updates, both plaintext and encrypted, set this argument to C(all). - Not applied when C(replace) is set to C(config); the candidate is loaded as-is via VyOS's native C(load), which has no equivalent filtering mechanism. type: str default: plaintext choices: - all - plaintext - encrypted - none """ EXAMPLES = """ - name: configure the remote device vyos.vyos.vyos_config: lines: - set system host-name {{ inventory_hostname }} - set service lldp - delete service dhcp-server - name: backup and load from file vyos.vyos.vyos_config: src: vyos.cfg backup: true - name: render a Jinja2 template onto the VyOS router vyos.vyos.vyos_config: match: enforce src: vyos_template.j2 - name: revert after ten minutes, if connection is lost vyos.vyos.vyos_config: src: vyos_template.j2 confirm: automatic - name: for idempotency, use full-form commands vyos.vyos.vyos_config: lines: # - set int eth eth2 description 'OUTSIDE' - set interface ethernet eth2 description 'OUTSIDE' - name: configurable backup path vyos.vyos.vyos_config: backup: true backup_options: filename: backup.cfg dir_path: /home/user - name: capture the complete hierarchical configuration for editing # replace=config requires the complete desired configuration in # hierarchical/bracket format -- never a partial one, and never flat # set-command format. `backup: true` alone won't work here: it captures # flat set-command output (via `show configuration commands`), which # replace=config's underlying `load` command rejects. Capture the # hierarchical form directly instead, edit it, then replace with the # edited whole, as shown here. vyos.vyos.vyos_command: commands: "show configuration" register: current_config - name: (edit current_config.stdout[0] as needed, save it locally, then) vyos.vyos.vyos_config: src: /home/user/edited_config.cfg replace: config """ RETURN = """ commands: description: - In C(replace=line) mode (default), the list of set/delete commands sent to the device. - In C(replace=config) mode, contains only the single C(load ) command actually issued to the device -- not an itemized diff. See C(diff) for the actual change content, sourced from VyOS's own C(compare) output. returned: always type: list sample: ['...', '...'] filtered: description: - The list of configuration commands removed to avoid a load failure. - Not populated when C(replace) is set to C(config). 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 os import re import tempfile -from ansible.module_utils._text import to_bytes, to_text from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.common.text.converters import to_bytes, to_text from ansible.module_utils.connection import ConnectionError from ansible_collections.vyos.vyos.plugins.module_utils.network.vyos.vyos import ( copy_file, get_config, get_connection, load_config, run_commands, ) DEFAULT_COMMENT = "configured by vyos_config" PASSWORD_NEEDLE = re.compile( r"(?:set|delete) system login user \S+ authentication (encrypted|plaintext)-password", ) # diff_match=enforce's scoping can collapse an entire untouched subtree into # a single parent delete (e.g. "delete system login" when a candidate # touches system without restating login, or "delete system login user # admin" without a specific authentication line). PASSWORD_NEEDLE can't see # into a collapsed delete to know whether it removes a password -- since # real users almost always have one configured, treat any subtree-level # login deletion as password-bearing by default, same conservative stance # as PASSWORD_NEEDLE itself. LOGIN_SUBTREE_DELETE_NEEDLE = re.compile( r"^delete system login(?:\s+user\s+\S+(?:\s+authentication)?)?\s*$", ) def sanitize_config(config, result, allow): result["filtered"] = list() if allow == "all": return index_to_filter = list() for index, line in enumerate(list(config)): found = PASSWORD_NEEDLE.search(line) if found is not None: if allow == found[1]: continue result["filtered"].append(line) index_to_filter.append(index) continue if LOGIN_SUBTREE_DELETE_NEEDLE.match(line.strip()): 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 get_candidate(module): contents = module.params["src"] or module.params["lines"] if module.params["src"]: contents = contents.splitlines() if len(contents) > 0: line = contents[0].split() if len(line) > 0 and line[0] in ("set", "delete"): contents = format_commands(contents) contents = "\n".join(contents) return contents def format_commands(commands): """ 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 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") allow_password_change = module.params["allow_password_change"] sanitize_config(commands, result, allow=allow_password_change) result["commands"] = commands confirm_param = module.params["confirm"] if confirm_param is None: confirm_param = "automatic" if module.params["match"] == "enforce" else "none" commit = not module.check_mode comment = module.params["comment"] confirm = None if confirm_param in ("automatic", "manual"): confirm = module.params["confirm_timeout"] diff = None if commands: diff = load_config(module, commands, commit=commit, comment=comment, confirm=confirm) if confirm_param == "automatic" and not module.check_mode: run_commands(module, ["configure", "confirm", "exit"]) 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 run_replace_config(module, result): # replace=config: push the full candidate to the device and let VyOS's # own `load` command perform the replacement natively, rather than # computing a set/delete diff in Python. # # Deliberately smaller than cisco.iosxr's equivalent implementation: # - No bidirectional pre-diff to decide whether anything changed -- # confirmed on real VyOS 1.5 hardware that `load` of an # already-applied file, followed by `compare`, natively reports # "No changes between working and active configurations" with no # Python-side pre-check needed. # - No special `replace=` argument threaded through load_config()/ # edit_config() -- confirmed that `load ` behaves as an ordinary # configuration command through the existing configure/compare/commit # flow already implemented in Cliconf.edit_config(), unmodified. # # Candidate format requirement (hierarchical/bracket, not flat # set/delete) is enforced by VyOS's own `load` parser, not by this # module -- confirmed empirically: flat set-command input produces # "ValueError: Failed to parse config: Syntax error...". # module.params["src"] is already the rendered file *content* by this # point, not a path -- netcommon's generic action plugin for src-based # network config modules reads the local file and substitutes its # (Jinja2-rendered) content into this param before the module runs. Same # assumption get_candidate() already relies on elsewhere in this file. candidate = to_bytes(module.params["src"], errors="surrogate_or_strict") tmp = tempfile.NamedTemporaryFile(delete=False) local_path = tmp.name try: tmp.write(candidate) tmp.close() # Fixed remote filename, always overwritten -- same precedent as # cisco.iosxr.iosxr_config's copy_file_to_node(), which always # writes to the same "/harddisk:/ansible_config.txt". Avoids # per-run temp-file accumulation on the device, at the accepted # cost (shared with iosxr_config) that two concurrent replace=config # runs against the same host could race on this path. remote_path = "/tmp/ansible_vyos_replace.cfg" copy_file(module, local_path, remote_path, "scp") finally: os.unlink(local_path) confirm_param = module.params["confirm"] if confirm_param is None: confirm_param = "none" commit = not module.check_mode comment = module.params["comment"] confirm = None if confirm_param in ("automatic", "manual"): confirm = module.params["confirm_timeout"] diff = load_config( module, ["load %s" % remote_path], commit=commit, comment=comment, confirm=confirm, ) if confirm_param == "automatic" and diff and not module.check_mode: run_commands(module, ["configure", "confirm", "exit"]) result["commands"] = ["load %s" % remote_path] result["filtered"] = [] result["changed"] = bool(diff) 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", elements="str"), match=dict(default="line", choices=["line", "enforce", "none"]), comment=dict(default=DEFAULT_COMMENT), confirm=dict(choices=["automatic", "manual", "none"], default=None), confirm_timeout=dict(type="int", default=10), config=dict(), backup=dict(type="bool", default=False), backup_options=dict(type="dict", options=backup_spec), save=dict(type="bool", default=False), replace=dict(type="str", default="line", choices=["line", "config"]), allow_password_change=dict( default="plaintext", choices=["all", "encrypted", "plaintext", "none"], ), ) mutually_exclusive = [("lines", "src")] required_if = [("replace", "config", ["src"])] module = AnsibleModule( argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True, ) warnings = list() result = dict(changed=False, warnings=warnings) if module.params["backup"]: result["__backup__"] = get_config(module=module) if module.params["replace"] == "config": run_replace_config(module, result) elif 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 not in { "[edit]", "No changes between working and saved configurations.\n\n[edit]", }: if not module.check_mode: run_commands(module, commands=["save"]) result["changed"] = True run_commands(module, commands=["exit"]) if ( result.get("changed") and module.params["replace"] != "config" and any((module.params["src"], module.params["lines"])) ): msg = ( "To ensure idempotency and correct diff the input configuration lines should be" " similar to how they appear if present in" " the running configuration on device" ) if module.params["src"]: msg += " including the indentation" if "warnings" in result: result["warnings"].append(msg) else: result["warnings"] = msg module.exit_json(**result) if __name__ == "__main__": main() diff --git a/plugins/modules/vyos_vlan.py b/plugins/modules/vyos_vlan.py index d2e004f8..82097676 100644 --- a/plugins/modules/vyos_vlan.py +++ b/plugins/modules/vyos_vlan.py @@ -1,390 +1,391 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Ansible by Red Hat, inc # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type DOCUMENTATION = """ module: vyos_vlan author: Trishna Guha (@trishnaguha) short_description: Manage VLANs on VyOS network devices description: - This module provides declarative management of VLANs on VyOS network devices. version_added: 1.0.0 notes: - Tested against VyOS 1.3.8, 1.4.2, the upcoming 1.5, and the rolling release of spring 2025. - This module works with connection C(ansible.netcommon.network_cli). See L(the VyOS OS Platform Options,../network/user_guide/platform_vyos.html). options: name: description: - Name of the VLAN. type: str address: description: - Configure Virtual interface address. type: str vlan_id: description: - ID of the VLAN. Range 0-4094. type: int interfaces: description: - List of interfaces that should be associated to the VLAN. type: list elements: str associated_interfaces: description: - This is a intent option and checks the operational state of the for given vlan C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vlan on device it will result in failure. type: list elements: str delay: description: - Delay the play should wait to check for declarative intent params values. default: 10 type: int aggregate: description: List of VLANs definitions. type: list elements: dict suboptions: name: description: - Name of the VLAN. type: str address: description: - Configure Virtual interface address. type: str vlan_id: description: - ID of the VLAN. Range 0-4094. type: int required: true interfaces: description: - List of interfaces that should be associated to the VLAN. type: list elements: str required: true associated_interfaces: description: - This is a intent option and checks the operational state of the for given vlan C(name) for associated interfaces. If the value in the C(associated_interfaces) does not match with the operational state of vlan on device it will result in failure. type: list elements: str delay: description: - Delay the play should wait to check for declarative intent params values. type: int state: description: - State of the VLAN configuration. type: str choices: - present - absent purge: description: - Purge VLANs not defined in the I(aggregate) parameter. default: false type: bool state: description: - State of the VLAN configuration. default: present type: str choices: - present - absent extends_documentation_fragment: - vyos.vyos.vyos """ EXAMPLES = """ - name: Create vlan vyos.vyos.vyos_vlan: vlan_id: 100 name: vlan-100 interfaces: eth1 state: present - name: Add interfaces to VLAN vyos.vyos.vyos_vlan: vlan_id: 100 interfaces: - eth1 - eth2 - name: Configure virtual interface address vyos.vyos.vyos_vlan: vlan_id: 100 interfaces: eth1 address: 172.26.100.37/24 - name: vlan interface config + intent vyos.vyos.vyos_vlan: vlan_id: 100 interfaces: eth0 associated_interfaces: - eth0 - name: vlan intent check vyos.vyos.vyos_vlan: vlan_id: 100 associated_interfaces: - eth3 - eth4 - name: Delete vlan vyos.vyos.vyos_vlan: vlan_id: 100 interfaces: eth1 state: absent """ RETURN = """ commands: description: The list of configuration mode commands to send to the device returned: always type: list sample: - set interfaces ethernet eth1 vif 100 description VLAN 100 - set interfaces ethernet eth1 vif 100 address 172.26.100.37/24 - delete interfaces ethernet eth1 vif 100 """ import re import time from copy import deepcopy -from ansible.module_utils._text import to_text from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.common.text.converters import to_text from ansible.module_utils.common.validation import check_required_one_of 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, ) def search_obj_in_list(vlan_id, lst): obj = list() for o in lst: if o["vlan_id"] == vlan_id: obj.append(o) return obj def map_obj_to_commands(updates, module): commands = list() want, have = updates purge = module.params["purge"] for w in want: vlan_id = w["vlan_id"] name = w["name"] address = w["address"] state = w["state"] obj_in_have = search_obj_in_list(vlan_id, have) if state == "absent": if obj_in_have: for obj in obj_in_have: for i in obj["interfaces"]: commands.append("delete interfaces ethernet {0} vif {1}".format(i, vlan_id)) elif state == "present": if not obj_in_have: if w["interfaces"] and w["vlan_id"]: for i in w["interfaces"]: cmd = "set interfaces ethernet {0} vif {1}".format(i, vlan_id) if w["name"]: commands.append(cmd + " description {0}".format(name)) elif w["address"]: commands.append(cmd + " address {0}".format(address)) else: commands.append(cmd) if purge: for h in have: obj_in_want = search_obj_in_list(h["vlan_id"], want) if not obj_in_want: for i in h["interfaces"]: commands.append( "delete interfaces ethernet {0} vif {1}".format(i, h["vlan_id"]), ) return commands 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 not d["vlan_id"]: module.fail_json(msg="vlan_id is required") d["vlan_id"] = str(d["vlan_id"]) try: check_required_one_of(module.required_one_of, item) except TypeError as exc: module.fail_json(to_text(exc)) obj.append(d) else: obj.append( { "vlan_id": str(module.params["vlan_id"]), "name": module.params["name"], "address": module.params["address"], "state": module.params["state"], "interfaces": module.params["interfaces"], "associated_interfaces": module.params["associated_interfaces"], }, ) return obj def map_config_to_obj(module): objs = [] output = run_commands(module, "show interfaces") lines = output[0].strip().splitlines()[3:] for line in lines: splitted_line = re.split(r"\s{2,}", line.strip()) obj = {} eth = splitted_line[0].strip("'") if eth.startswith("eth") and "." in eth: obj["interfaces"] = [] interface = eth.split(".")[0] obj["interfaces"].append(interface) obj["vlan_id"] = eth.split(".")[-1] if splitted_line[1].strip("'") != "-": obj["address"] = splitted_line[1].strip("'") if len(splitted_line) > 3: obj["name"] = splitted_line[3].strip("'") obj["state"] = "present" objs.append(obj) return objs def check_declarative_intent_params(want, module, result): have = None obj_interface = list() is_delay = False for w in want: if w.get("associated_interfaces") is None: continue if result["changed"] and not is_delay: time.sleep(module.params["delay"]) is_delay = True if have is None: have = map_config_to_obj(module) obj_in_have = search_obj_in_list(w["vlan_id"], have) if obj_in_have: for obj in obj_in_have: obj_interface.extend(obj["interfaces"]) for w in want: if w.get("associated_interfaces") is None: continue for i in w["associated_interfaces"]: if (set(obj_interface) - set(w["associated_interfaces"])) != set([]): module.fail_json( msg="Interface {0} not configured on vlan {1}".format(i, w["vlan_id"]), ) def main(): """main entry point for module execution""" element_spec = dict( vlan_id=dict(type="int"), name=dict(), address=dict(), interfaces=dict(type="list", elements="str"), associated_interfaces=dict(type="list", elements="str"), delay=dict(default=10, type="int"), state=dict(default="present", choices=["present", "absent"]), ) aggregate_spec = deepcopy(element_spec) aggregate_spec["vlan_id"].update(required=True) aggregate_spec["interfaces"].update(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), purge=dict(default=False, type="bool"), ) argument_spec.update(element_spec) required_one_of = [ ["vlan_id", "aggregate"], ["aggregate", "interfaces", "associated_interfaces"], ] mutually_exclusive = [["vlan_id", "aggregate"]] module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, ) 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 check_declarative_intent_params(want, module, result) module.exit_json(**result) if __name__ == "__main__": main() diff --git a/tests/unit/mock/loader.py b/tests/unit/mock/loader.py index 2828f38e..d13968ce 100644 --- a/tests/unit/mock/loader.py +++ b/tests/unit/mock/loader.py @@ -1,116 +1,117 @@ # (c) 2012-2014, Michael DeHaan # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # Make coding more python3-ish from __future__ import absolute_import, division, print_function + __metaclass__ = type import os from ansible.errors import AnsibleParserError -from ansible.module_utils._text import to_bytes, to_text +from ansible.module_utils.common.text.converters import to_bytes, to_text from ansible.parsing.dataloader import DataLoader class DictDataLoader(DataLoader): def __init__(self, file_mapping=None): file_mapping = {} if file_mapping is None else file_mapping assert isinstance(file_mapping, dict) super(DictDataLoader, self).__init__() self._file_mapping = file_mapping self._build_known_directories() self._vault_secrets = None def load_from_file(self, path, cache=True, unsafe=False): path = to_text(path) if path in self._file_mapping: return self.load(self._file_mapping[path], path) return None # TODO: the real _get_file_contents returns a bytestring, so we actually convert the # unicode/text it's created with to utf-8 def _get_file_contents(self, file_name): path = to_text(file_name) if path in self._file_mapping: return (to_bytes(self._file_mapping[file_name]), False) else: raise AnsibleParserError("file not found: %s" % file_name) def path_exists(self, path): path = to_text(path) return path in self._file_mapping or path in self._known_directories def is_file(self, path): path = to_text(path) return path in self._file_mapping def is_directory(self, path): path = to_text(path) return path in self._known_directories def list_directory(self, path): ret = [] path = to_text(path) for x in list(self._file_mapping.keys()) + self._known_directories: if x.startswith(path): if os.path.dirname(x) == path: ret.append(os.path.basename(x)) return ret def is_executable(self, path): # FIXME: figure out a way to make paths return true for this return False def _add_known_directory(self, directory): if directory not in self._known_directories: self._known_directories.append(directory) def _build_known_directories(self): self._known_directories = [] for path in self._file_mapping: dirname = os.path.dirname(path) while dirname not in ("/", ""): self._add_known_directory(dirname) dirname = os.path.dirname(dirname) def push(self, path, content): rebuild_dirs = False if path not in self._file_mapping: rebuild_dirs = True self._file_mapping[path] = content if rebuild_dirs: self._build_known_directories() def pop(self, path): if path in self._file_mapping: del self._file_mapping[path] self._build_known_directories() def clear(self): self._file_mapping = dict() self._known_directories = [] def get_basedir(self): return os.getcwd() def set_vault_secrets(self, vault_secrets): self._vault_secrets = vault_secrets diff --git a/tests/unit/mock/procenv.py b/tests/unit/mock/procenv.py index 2ae0c173..fceb6f1b 100644 --- a/tests/unit/mock/procenv.py +++ b/tests/unit/mock/procenv.py @@ -1,95 +1,96 @@ # (c) 2016, Matt Davis # (c) 2016, Toshio Kuratomi # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # Make coding more python3-ish from __future__ import absolute_import, division, print_function + __metaclass__ = type import json import sys from contextlib import contextmanager from io import BytesIO, StringIO -from ansible.module_utils._text import to_bytes +from ansible.module_utils.common.text.converters import to_bytes from ansible_collections.vyos.vyos.tests.unit.compat import unittest @contextmanager def swap_stdin_and_argv(stdin_data="", argv_data=tuple()): """ context manager that temporarily masks the test runner's values for stdin and argv """ real_stdin = sys.stdin real_argv = sys.argv # if PY3: fake_stream = StringIO(stdin_data) fake_stream.buffer = BytesIO(to_bytes(stdin_data)) # else: # fake_stream = BytesIO(to_bytes(stdin_data)) try: sys.stdin = fake_stream sys.argv = argv_data yield finally: sys.stdin = real_stdin sys.argv = real_argv @contextmanager def swap_stdout(): """ context manager that temporarily replaces stdout for tests that need to verify output """ old_stdout = sys.stdout # if PY3: fake_stream = StringIO() # else: # fake_stream = BytesIO() try: sys.stdout = fake_stream yield fake_stream finally: sys.stdout = old_stdout class ModuleTestCase(unittest.TestCase): def setUp(self, module_args=None): if module_args is None: module_args = { "_ansible_remote_tmp": "/tmp", "_ansible_keep_remote_files": False, } args = json.dumps(dict(ANSIBLE_MODULE_ARGS=module_args)) # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually self.stdin_swap = swap_stdin_and_argv(stdin_data=args) self.stdin_swap.__enter__() def tearDown(self): # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually self.stdin_swap.__exit__(None, None, None) diff --git a/tests/unit/mock/vault_helper.py b/tests/unit/mock/vault_helper.py index 4c6c890c..ca15f98e 100644 --- a/tests/unit/mock/vault_helper.py +++ b/tests/unit/mock/vault_helper.py @@ -1,39 +1,40 @@ # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see . # Make coding more python3-ish from __future__ import absolute_import, division, print_function + __metaclass__ = type -from ansible.module_utils._text import to_bytes +from ansible.module_utils.common.text.converters import to_bytes from ansible.parsing.vault import VaultSecret class TextVaultSecret(VaultSecret): """A secret piece of text. ie, a password. Tracks text encoding. The text encoding of the text may not be the default text encoding so we keep track of the encoding so we encode it to the same bytes.""" def __init__(self, text, encoding=None, errors=None, _bytes=None): super(TextVaultSecret, self).__init__() self.text = text self.encoding = encoding or "utf-8" self._bytes = _bytes self.errors = errors or "strict" @property def bytes(self): """The text encoded with encoding, unless we specifically set _bytes.""" return self._bytes or to_bytes(self.text, encoding=self.encoding, errors=self.errors) diff --git a/tests/unit/modules/conftest.py b/tests/unit/modules/conftest.py index b084d2f0..a20ebf78 100644 --- a/tests/unit/modules/conftest.py +++ b/tests/unit/modules/conftest.py @@ -1,30 +1,31 @@ # Copyright (c) 2017 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function + __metaclass__ = type import json import pytest -from ansible.module_utils._text import to_bytes from ansible.module_utils.common._collections_compat import MutableMapping +from ansible.module_utils.common.text.converters import to_bytes @pytest.fixture def patch_ansible_module(request, mocker): if isinstance(request.param, str): args = request.param elif isinstance(request.param, MutableMapping): if "ANSIBLE_MODULE_ARGS" not in request.param: request.param = {"ANSIBLE_MODULE_ARGS": request.param} if "_ansible_remote_tmp" not in request.param["ANSIBLE_MODULE_ARGS"]: request.param["ANSIBLE_MODULE_ARGS"]["_ansible_remote_tmp"] = "/tmp" if "_ansible_keep_remote_files" not in request.param["ANSIBLE_MODULE_ARGS"]: request.param["ANSIBLE_MODULE_ARGS"]["_ansible_keep_remote_files"] = False args = json.dumps(request.param) else: raise Exception("Malformed data to the patch_ansible_module pytest fixture") mocker.patch("ansible.module_utils.basic._ANSIBLE_ARGS", to_bytes(args)) diff --git a/tests/unit/modules/utils.py b/tests/unit/modules/utils.py index c2a19070..55960250 100644 --- a/tests/unit/modules/utils.py +++ b/tests/unit/modules/utils.py @@ -1,57 +1,58 @@ from __future__ import absolute_import, division, print_function + __metaclass__ = type import json import unittest from unittest.mock import patch from ansible.module_utils import basic -from ansible.module_utils._text import to_bytes +from ansible.module_utils.common.text.converters import to_bytes def set_module_args(args): if "_ansible_remote_tmp" not in args: args["_ansible_remote_tmp"] = "/tmp" if "_ansible_keep_remote_files" not in args: args["_ansible_keep_remote_files"] = False args = json.dumps({"ANSIBLE_MODULE_ARGS": args}) basic._ANSIBLE_ARGS = to_bytes(args) profile = "legacy" basic._ANSIBLE_PROFILE = profile class AnsibleExitJson(Exception): pass class AnsibleFailJson(Exception): pass def exit_json(*args, **kwargs): if "changed" not in kwargs: kwargs["changed"] = False raise AnsibleExitJson(kwargs) def fail_json(*args, **kwargs): kwargs["failed"] = True raise AnsibleFailJson(kwargs) class ModuleTestCase(unittest.TestCase): def setUp(self): self.mock_module = patch.multiple( basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json, ) self.mock_module.start() self.mock_sleep = patch("time.sleep") self.mock_sleep.start() set_module_args({}) self.addCleanup(self.mock_module.stop) self.addCleanup(self.mock_sleep.stop)