如何在 ansible 中处理长 运行 命令?

how to handle long running commnads in ansilbe?

为了确保像 (apt-mirror) 这样需要数小时才能同步的耗时命令,是否有更好的方法来处理它们,以便 anible 继续工作。

因此,您正在寻找一个 asynchronous task,此类任务可以与同级任务一起使用,即 async_status,以便检查(返回)已注册异步的状态任务。

这里有一个简单的示例:

- 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

回顾一下:

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]