0

I'm having an issue when running a Python script using the win_command module. The playbook execution hangs indefinitely when the Python script starts a Tomcat process which is supposed to keep running even once the script completes. If I were to manually kill the Tomcat process, the Ansible playbook completes.

---
- name: Restore product
  win_command: 'python restore-product.py'
  args:
    chdir: C:\temp  

I have tried the following within the Python script hoping that Ansible would not be able to track the launched process, but have had no luck:

subprocess.Popen('start /cmd /c service.bat startup', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

sys.exit(0)
Zeitounator
  • 38,476
  • 7
  • 53
  • 66
Eric27710
  • 85
  • 1
  • 6
  • What happens when you manually runs this piece of Python from a Windows host? Does it correctly gives you back the prompt or does it also hangs indefinitely, as does your playbook? – β.εηοιτ.βε Feb 07 '22 at 17:50
  • If I run the Python script from the Windows host it will exit at sys.exit(0) and return back to a command prompt. – Eric27710 Feb 07 '22 at 19:08
  • I'd bet the problem is that the process is still attached to the current terminal . So the python script is done but the terminal still has a running process attached to stdin/out/err and ansible task does not exit. Can you try with something like `subprocess.Popen('start /cmd /c service.bat startup', stdin=None, stdout=None, stderr=None, close_fds=True, shell=False)`? (see comments in [this question](https://stackoverflow.com/questions/51538651/how-to-detach-a-program-ran-by-subprocess-call)). Study Popen doc for more options to try. – Zeitounator Feb 07 '22 at 20:37
  • 1
    Friendly note: running Tomcat as a service would probably ease your life a lot. – Zeitounator Feb 07 '22 at 20:39
  • Thanks a lot for your suggestions @Zeitounator! I will give that a try. You are correct about running Tomcat as a service as when I tried this before Ansible works fine except I need to run Tomcat as a command line service to workaround another issue (which is a long story :) ). I will update the post after I tried the Python changes – Eric27710 Feb 07 '22 at 23:12
  • I suggest you give some background about this "other long story issue" because you might very well be in an [x/y problem](https://xyproblem.info) here and I'm almost sure some windows experts (i.e. not me;)) know how to fix that inside a running service. – Zeitounator Feb 07 '22 at 23:26

1 Answers1

0

Do not use Python's popen function and rather go for spawn() as described here: https://stackoverflow.com/a/1196122/4222206

Queeg
  • 7,748
  • 1
  • 16
  • 42
  • I tried the following on Windows: `os.spawnl(os.P_NOWAIT, sys.executable, 'C:\tomcat\bin\service.bat startup')` which returns a process ID of '0' without the process being started. Are I missing something? – Eric27710 Feb 09 '22 at 15:48