Ansible is really picking up the market because of it’s simplicity and have a long way to reach Puppet. In this post we will see on how to execute remote commands in background. Advantages of running commands in background is of two folds

1)We can run two tasks at a time one background and continue with other tasks.
2)We can effectively reduce time consumption of your tasks.

Running commands/tasks in background can be achieved with two ansible modules.
1)async module
2)at module

What is async module?

By default ansible will run tasks one after the other in sequentially. This effectively block others tasks to start. If you want them to run parallel we can use async module. So that tasks which take more time can be placed in background and continue with shorter tasks.

Syntax:

	- name: task name

	  shell: task

	  async: <Total time for above task to complete>

	  poll: <poll interval>

	 

Example

	- name: Update sources.list file

	  shell: apt-get update

	  async: 40

	  poll: 5

the above code will try to update Ubuntu sources.list file and it takes 40 seconds to complete. In order this background task to complete successfully we have to make sure our SSH connections stays alive for that we can use poll interval which can keep our SSH session alive.

The disadvantage of this is you should know typical time of task completion. If you want to just "fire and forgot" use classic at command as nohup command &, disown will not work.

Syntax:

	- name: Task to execute

	  at: command="command-to-execute" count=<number> unit's="type of time" 

Example:

	- name: Update sources.list file

	  at: command="apt-get update" count=1 unit's="minutes"

The above command will execute apt-get update command after 1 minute. The unit’s can be anything like minutes, hours, days, weeks

If you are not satisfied with above two methods, you can create a service in your Linux box and start that service using service module.

The following two tabs change content below.
Mr Surendra Anne is from Vijayawada, Andhra Pradesh, India. He is a Linux/Open source supporter who believes in Hard work, A down to earth person, Likes to share knowledge with others, Loves dogs, Likes photography. He works as Devops Engineer with Taggle systems, an IOT automatic water metering company, Sydney . You can contact him at surendra (@) linuxnix dot com.