diff --git a/lib/ansible/module_utils/network/ios/ios.py b/lib/ansible/module_utils/network/ios/ios.py index fa9c8e2751..d9318cd024 100644 --- a/lib/ansible/module_utils/network/ios/ios.py +++ b/lib/ansible/module_utils/network/ios/ios.py @@ -122,7 +122,11 @@ def to_commands(module, commands): def run_commands(module, commands, check_rc=True): connection = get_connection(module) - return connection.run_commands(commands=commands, check_rc=check_rc) + try: + out = connection.run_commands(commands=commands, check_rc=check_rc) + return out + except ConnectionError as exc: + module.fail_json(msg=to_text(exc)) def load_config(module, commands): diff --git a/lib/ansible/plugins/action/ios.py b/lib/ansible/plugins/action/ios.py index 5e531dbf32..f2ad0de7d9 100644 --- a/lib/ansible/plugins/action/ios.py +++ b/lib/ansible/plugins/action/ios.py @@ -24,7 +24,7 @@ import copy from ansible import constants as C from ansible.module_utils._text import to_text -from ansible.module_utils.connection import Connection +from ansible.module_utils.connection import Connection, ConnectionError from ansible.plugins.action.normal import ActionModule as _ActionModule from ansible.module_utils.network.common.utils import load_provider from ansible.module_utils.network.ios.ios import ios_provider_spec @@ -86,11 +86,14 @@ class ActionModule(_ActionModule): socket_path = self._connection.socket_path conn = Connection(socket_path) - out = conn.get_prompt() - while to_text(out, errors='surrogate_then_replace').strip().endswith(')#'): - display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr) - conn.send_command('exit') + try: out = conn.get_prompt() + while to_text(out, errors='surrogate_then_replace').strip().endswith(')#'): + display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr) + conn.send_command('exit') + out = conn.get_prompt() + except ConnectionError as exc: + return {'failed': True, 'msg': to_text(exc)} result = super(ActionModule, self).run(task_vars=task_vars) return result