2
votes

Using Ansible 1.7, I am executing multiple asynchronous tasks in a loop, and checking on their status with async_status with a 30-second timeout:

- name: Some long-running task
  shell: "./some_task {{ item }}"
  loop: "{{ list_of_params }}"
  async: 30
  poll: 0
  register: my_task

- name: Check async tasks for completion
  async_status:
    jid: "{{ item.ansible_job_id }}"
  register: my_task_results
  until: my_task_results.finished
  retries: 30
  delay: 1
  loop: "{{ my_task.results }}"

This works well, and the async_status task fails if any of the shell commands return non-zero return-code, or if "my_task_results.finished" is not true within 30 seconds.

Unfortunately, the error message is not helpful when the "until" condition is not met in time. The returned values include:

  • changed: false
  • msg: "All items completed"
  • results: [ array of results from shell task above ]
  • changed: false
  • failed: true
  • finished: 0

Particularly, the "All items completed" message is misleading.

Is there a way to produce a meaningful error message in this case? I can add a "failed_when" option, with an additional "Fail" task to check condition (finished == 0) to display a custom error message (Something to the effect of "Some long-running task did not complete in time"), but this seems inelegant.

1

1 Answers

0
votes

I think your solution will be fine in this case.

Please look to Official Ansible Docs: https://docs.ansible.com/ansible/2.5/user_guide/playbooks_loops.html#id10

Here you can find your method:

- name: Fail if return code is not 0
  fail:
    msg: "The command ({{ item.cmd }}) did not have a 0 return code"
  when: item.rc != 0
  loop: "{{ echo.results }}"

Sometimes when I need more beauty - more descriptive output I'm using template/file, then with a registered variable in the task, you can customize your output.

For example: 
- name:
  template:
... 

- shell: cat <template_location>.yml
  register: stack_test

- debug:
    msg: "{{ stack_test.stdout }}"