Tuesday, April 26, 2022

[SOLVED] how to handle long running commnads in ansilbe?

Issue

To make sure that the time consuming commands like (apt-mirror) which takes hours to sync, is there any better approach to handle them so that the anible would continue to work.


Solution

So, you are looking for an asynchronous task, those kind of task can come with a sibling, which is async_status, in order to check (back) on the status of a registered asynchronous task.

Here is a simple example on how it could look:

- hosts: localhost
  gather_facts: no

  tasks:
    - name: Run an async task
      shell: sleep 30
      ## Let it run for 5 minutes
      async: 300
      poll: 0
      ## We are registering the task, so we can get its status later
      register: long_runnging_task

    - debug:
        msg: "I am another task running in between"

    - name: Check on an async task
      async_status:
        jid: "{{ long_runnging_task.ansible_job_id }}"
      register: job_result
      until: job_result.finished
      ## Recheck this job status
      ## 30 times, leaving 10 seconds
      ## of interval between each retry 
      retries: 30
      delay: 10

Which gives the recap:

PLAY [localhost] *************************************************************

TASK [Run an async task] *****************************************************
changed: [localhost]

TASK [debug] *****************************************************************
ok: [localhost] => 
  msg: I am another task running in between

TASK [Check on an async task] ************************************************
FAILED - RETRYING: [localhost]: Check on an async task (30 retries left).
FAILED - RETRYING: [localhost]: Check on an async task (29 retries left).
FAILED - RETRYING: [localhost]: Check on an async task (28 retries left).
changed: [localhost]


Answered By - β.εηοιτ.βε
Answer Checked By - Mary Flores (WPSolving Volunteer)