summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md2
-rw-r--r--changelogs/fragments/t8989_snmp_server_core7.yml4
-rw-r--r--docs/vyos.rest.vyos_command_module.rst16
-rw-r--r--plugins/modules/vyos_command.py40
-rw-r--r--tests/unit/modules/test_vyos_command.py72
5 files changed, 126 insertions, 8 deletions
diff --git a/README.md b/README.md
index 1b25f56..2a655d1 100644
--- a/README.md
+++ b/README.md
@@ -86,7 +86,7 @@ collections:
### Httpapi plugins
Name | Description
--- | ---
-[vyos.rest.vyos](https://github.com/vyos/rest.vyos/blob/main/docs/vyos.rest.vyos_httpapi.rst)|HttpApi plugin for VyOS REST API
+[vyos.rest.vyos](https://github.com/vyos/rest.vyos/blob/main/docs/vyos.rest.vyos_httpapi.rst)|VyOS REST API
### Modules
Name | Description
diff --git a/changelogs/fragments/t8989_snmp_server_core7.yml b/changelogs/fragments/t8989_snmp_server_core7.yml
new file mode 100644
index 0000000..395078f
--- /dev/null
+++ b/changelogs/fragments/t8989_snmp_server_core7.yml
@@ -0,0 +1,4 @@
+---
+bugfixes:
+ - vyos_command - fail the task when the device rejects a command, instead of returning an ``ERROR:`` entry in ``stdout``.
+ - vyos_command - a command the device rejects is no longer retried.
diff --git a/docs/vyos.rest.vyos_command_module.rst b/docs/vyos.rest.vyos_command_module.rst
index 7075ec6..56354ca 100644
--- a/docs/vyos.rest.vyos_command_module.rst
+++ b/docs/vyos.rest.vyos_command_module.rst
@@ -134,6 +134,7 @@ Notes
- ``ansible_network_os`` must be set to ``vyos.rest.vyos``.
- Only ``show`` commands are supported via the REST API.
- Commands are passed as path lists to the ``/show`` endpoint.
+ - A command the device rejects fails the task at once and is not retried. ``stdout`` then holds the output of the commands that ran before it.
@@ -194,6 +195,21 @@ Common return values are documented `here <https://docs.ansible.com/ansible/late
<tr>
<td colspan="1">
<div class="ansibleOptionAnchor" id="return-"></div>
+ <b>failed_command</b>
+ <a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
+ <div style="font-size: small">
+ <span style="color: purple">raw</span>
+ </div>
+ </td>
+ <td>failed, when a command was rejected</td>
+ <td>
+ <div>The command the device rejected.</div>
+ <br/>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="1">
+ <div class="ansibleOptionAnchor" id="return-"></div>
<b>failed_conditions</b>
<a class="ansibleOptionLink" href="#return-" title="Permalink to this return value"></a>
<div style="font-size: small">
diff --git a/plugins/modules/vyos_command.py b/plugins/modules/vyos_command.py
index d688251..77bd318 100644
--- a/plugins/modules/vyos_command.py
+++ b/plugins/modules/vyos_command.py
@@ -59,6 +59,8 @@ notes:
- C(ansible_network_os) must be set to C(vyos.rest.vyos).
- Only C(show) commands are supported via the REST API.
- Commands are passed as path lists to the C(/show) endpoint.
+ - A command the device rejects fails the task at once and is not retried. C(stdout) then holds
+ the output of the commands that ran before it.
"""
EXAMPLES = r"""
@@ -112,12 +114,16 @@ failed_conditions:
description: List of conditions that failed.
returned: failed
type: list
+failed_command:
+ description: The command the device rejected.
+ returned: failed, when a command was rejected
+ type: raw
"""
import time
from ansible.module_utils.basic import AnsibleModule
-from ansible_collections.vyos.rest.plugins.module_utils.vyos import VyOSModule
+from ansible_collections.vyos.rest.plugins.module_utils.vyos import VyOSModule, VyOSRestError
def parse_command(cmd):
@@ -129,16 +135,31 @@ def parse_command(cmd):
return list(cmd)
+class CommandFailed(Exception):
+ """The device rejected a command. Carries the output collected before it."""
+
+ def __init__(self, command, error, stdout):
+ super(CommandFailed, self).__init__("%s: %s" % (command, error))
+ self.command = command
+ self.error = error
+ self.stdout = stdout
+
+
def run_commands(vyos, commands):
- """Run show commands and return stdout list."""
+ """Run show commands and return stdout list.
+
+ Raises CommandFailed, with the output of the commands that ran before it, when the
+ device rejects one. Any other exception is a bug and propagates.
+ """
+
stdout = []
for cmd in commands:
path = parse_command(cmd)
try:
result = vyos.show(path)
- stdout.append(result if result else "")
- except Exception as e:
- stdout.append("ERROR: %s" % str(e))
+ except VyOSRestError as exc:
+ raise CommandFailed(cmd, str(exc), stdout)
+ stdout.append(result if result else "")
return stdout
@@ -197,7 +218,14 @@ def main():
failed_conditions = []
for attempt in range(retries):
- stdout = run_commands(vyos, commands)
+ try:
+ stdout = run_commands(vyos, commands)
+ except CommandFailed as exc:
+ module.fail_json(
+ msg="command failed: %s: %s" % (exc.command, exc.error),
+ failed_command=exc.command,
+ stdout=exc.stdout,
+ )
if not wait_for:
break
diff --git a/tests/unit/modules/test_vyos_command.py b/tests/unit/modules/test_vyos_command.py
index 5b474f9..ec81e92 100644
--- a/tests/unit/modules/test_vyos_command.py
+++ b/tests/unit/modules/test_vyos_command.py
@@ -6,9 +6,12 @@ __metaclass__ = type
import unittest
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
+from ansible_collections.vyos.rest.plugins.module_utils.vyos import VyOSRestError
+from ansible_collections.vyos.rest.plugins.modules import vyos_command as command_module
from ansible_collections.vyos.rest.plugins.modules.vyos_command import (
+ CommandFailed,
evaluate_conditions,
parse_command,
run_commands,
@@ -107,5 +110,72 @@ class TestVyOSCommandRunCommands(unittest.TestCase):
self.assertEqual(result, [""])
+class TestVyOSCommandFailures(unittest.TestCase):
+ """CORE-7: a command the device rejects must fail the task, not hide in stdout."""
+
+ def setUp(self):
+ self.vyos = MagicMock()
+
+ def test_a_rejected_command_raises_with_the_earlier_output(self):
+ self.vyos.show.side_effect = ["out1", VyOSRestError("Invalid command (HTTP 400)")]
+ with self.assertRaises(CommandFailed) as ctx:
+ run_commands(self.vyos, ["show version", "show bogus"])
+ self.assertEqual(ctx.exception.command, "show bogus")
+ self.assertIn("Invalid command", ctx.exception.error)
+ self.assertEqual(ctx.exception.stdout, ["out1"])
+
+ def test_the_first_command_failing_leaves_no_output(self):
+ self.vyos.show.side_effect = VyOSRestError("boom")
+ with self.assertRaises(CommandFailed) as ctx:
+ run_commands(self.vyos, ["show version"])
+ self.assertEqual(ctx.exception.stdout, [])
+
+ def test_other_exceptions_are_bugs_and_propagate(self):
+ self.vyos.show.side_effect = RuntimeError("connection reset")
+ with self.assertRaises(RuntimeError):
+ run_commands(self.vyos, ["show version"])
+
+ def run_main(self, show_side_effect, **params):
+ module = MagicMock()
+ module.params = dict(
+ {
+ "commands": ["show version", "show bogus"],
+ "wait_for": None,
+ "match": "all",
+ "retries": 3,
+ "interval": 0,
+ },
+ **params,
+ )
+ module.fail_json.side_effect = SystemExit
+ self.vyos.show.side_effect = show_side_effect
+ with patch.object(command_module, "AnsibleModule", return_value=module):
+ with patch.object(command_module, "VyOSModule", return_value=self.vyos):
+ try:
+ command_module.main()
+ except SystemExit:
+ pass
+ return module
+
+ def test_main_fails_the_task_and_keeps_the_output_so_far(self):
+ module = self.run_main(["out1", VyOSRestError("Invalid command (HTTP 400)")])
+ kwargs = module.fail_json.call_args[1]
+ self.assertIn("command failed: show bogus", kwargs["msg"])
+ self.assertEqual(kwargs["failed_command"], "show bogus")
+ self.assertEqual(kwargs["stdout"], ["out1"])
+ module.exit_json.assert_not_called()
+
+ def test_a_rejected_command_is_not_retried(self):
+ module = self.run_main(VyOSRestError("boom"), wait_for=["result[0] contains x"])
+ self.assertEqual(self.vyos.show.call_count, 1)
+ module.fail_json.assert_called_once()
+
+ def test_main_still_succeeds_when_every_command_works(self):
+ module = self.run_main(["out1", "out2"])
+ module.fail_json.assert_not_called()
+ kwargs = module.exit_json.call_args[1]
+ self.assertEqual((kwargs["changed"], kwargs["stdout"]), (False, ["out1", "out2"]))
+
+
if __name__ == "__main__":
unittest.main()