How Do You Get an Ansible Command to Issue a Long-Running Bash Command and Keep Processing?

Problem scenario
You have a playbook that runs a shell command.  But this command never completes.  If you cancel the playbook, you find the processes started from the playbook cancel from the cancellation of the playbook too.  You want the process to keep running while Ansible moves to the next command.  You want processes to run in a detached way that is independent of the playbook execution itself.  You want the playbook to have a finite duration while allowing the Linux command to continue processing. What do you do to get the Ansible playbook to complete while leaving long-running (including processes that run indefinitely) Linux processes/commands running that were started by the playbook itself?

Root cause

The Ansible playbook generally waits for the Linux command to return a success or failure.  It does not keep processing until the Linux command is completed.

Possible solution #1
Prepend this string to the Bash command itself: "nohup "
Append this string, without the quotes, to the end of the Bash command: "> /dev/null 2>&1 &"

Possible solution #2
If the Linux command starts a service that runs indefinitely, create a foobar.service file where "foobar" is the name of the service.  Place this file in /etc/systemd/system/.   Now you can re-write your Ansible playbook to use the built in "service" module rather than the raw Linux commands.  To learn about how to create a .service file, look at solution #2 of this article.

Possible solution #3
Use the "async" and "poll" attributes.  Alternatively you can use the pause module after a long-running command such as the one above.  This link has more information.  The word "pause" is reserved and can take attributes "minutes" or "seconds".  Pausing for 10 seconds after the shell (or raw Linux) command can allow for the Ansible playbook to continue running while allowing the command to run on its own.

Leave a comment

Your email address will not be published. Required fields are marked *