在 Ansible 中等待异步任务会引发错误:'dict object'没有属性'ansible_job_id'



我在Ansible中生成了几个异步任务,并试图等待它们全部完成,然后再继续执行下一组任务(共9个(。以下是其中几个例子:

- name: EC2 spin up
  async: 6000
  poll: 0
  shell: # spin up an instance with a playbook
  register: ec2_item
  when: deployment_type == 'x' or deployment_type == 'y'
- name: EC2 spin up another
  async: 6000
  poll: 0
  shell: # # spin up another instance with a playbook
  register: ec2_item_again
  when: deployment_type == 'x' or deployment_type == 'y'

在这之后,我运行这个块来等待他们:

- name: Wait on EC2 Async Tasks
  async_status:
  jid: "{{ item.ansible_job_id }}"
  with_items:
    - "{{ ec2_item }}"
    - "{{ ec2_item_again }}"
  register: job_result
  until: job_result.finished
  retries: 60
  delay: 15

最终,事情结束了,但它在没有他跟随的情况下出错了:

fatal: [127.0.0.1]: FAILED! => {
    "msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'ansible_job_id'nnThe error appears to be in '/opt/app-root/src/playbooks/sb_build_flow.yml': line 201, column 7, but maynbe elsewhere in the file depending on the exact syntax problem.nnThe offending line appears to be:nn      delay: 6n    - async_status:n      ^ heren"
}

它试图寻找一个已经不存在的任务,但我不确定如何真正完成这项工作。同样,我只是想让Ansible也等异步任务完成后再继续。

根据文档async_status模块-获取异步任务的状态-示例jid至少有一个不正确的标识。

下面的最小示例似乎运行成功的

---
- hosts: test
  become: false
  gather_facts: false
  tasks:
  - name: Wait ONE
    shell:
      cmd: "sleep 15"
    async: 6000
    poll: 0
    register: ONE
  - name: Wait TWO
    shell:
      cmd: "sleep 15"
    async: 6000
    poll: 0
    register: TWO
  - name: Wait on tasks
    async_status:
      jid: "{{ item.ansible_job_id }}"
    loop: "[{{ ONE }}, {{ TWO }}]"
    loop_control:
      label: "{{ item.ansible_job_id }}"
    register: job_result
    until: job_result.finished
    retries: 60
    delay: 15

导致的输出

TASK [Wait ONE] *****************************************
changed: [test.example.com]
TASK [Wait TWO] *****************************************
changed: [test.example.com]
FAILED - RETRYING: Wait on tasks (60 retries left).
TASK [Wait on tasks] ************************************
changed: [test.example.com] => (item=229736317985.176035)
changed: [test.example.com] => (item=829194009194.176257)

进一步文档

  • 使用label限制环路输出

最新更新