From 029ccf9aa0cd490224bfcf403ed94bc397e3af63 Mon Sep 17 00:00:00 2001
From: Ricardo Carrillo Cruz <ricardo.carrillo.cruz@gmail.com>
Date: Wed, 1 Mar 2017 11:44:12 +0100
Subject: [PATCH] Check right CLI context is set on iosxr action plugin
 (#22108)

Fixes #21994
---
 lib/ansible/plugins/action/iosxr.py | 14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)

diff --git a/lib/ansible/plugins/action/iosxr.py b/lib/ansible/plugins/action/iosxr.py
index 3539b0b6b70..83fb1d2f5b9 100644
--- a/lib/ansible/plugins/action/iosxr.py
+++ b/lib/ansible/plugins/action/iosxr.py
@@ -64,19 +64,23 @@ class ActionModule(_ActionModule):
         socket_path = self._get_socket_path(pc)
         if not os.path.exists(socket_path):
             # start the connection if it isn't started
+            display.vvvv('calling open_shell()', pc.remote_addr)
             rc, out, err = connection.exec_command('open_shell()')
             if rc != 0:
                 return {'failed': True, 'msg': 'unable to open shell', 'rc': rc}
+        else:
+            # make sure we are in the right cli context which should be
+            # enable mode and not config module
+            rc, out, err = connection.exec_command('prompt()')
+            while str(out).strip().endswith(')#'):
+                display.vvvv('wrong context, sending exit to device', self._play_context.remote_addr)
+                connection.exec_command('exit')
+                rc, out, err = connection.exec_command('prompt()')
 
         task_vars['ansible_socket'] = socket_path
 
         result = super(ActionModule, self).run(tmp, task_vars)
 
-        # need to make sure to leave config mode if the module didn't clean up
-        rc, out, err = connection.exec_command('prompt()')
-        if str(out).strip().endswith(')#'):
-            connection.exec_command('exit')
-
         return result
 
     def _get_socket_path(self, play_context):