Skip to content

Instantly share code, notes, and snippets.

@ParagDoke
Last active February 24, 2022 12:07
Show Gist options
  • Save ParagDoke/5ddfc3d5647ce9b0110d1b9790090092 to your computer and use it in GitHub Desktop.
Save ParagDoke/5ddfc3d5647ce9b0110d1b9790090092 to your computer and use it in GitHub Desktop.
Conditionally loop over multiple ansible tasks
---
- name: test
hosts: localhost
connection: local
tasks:
- name: Invoke poller
vars:
url: http://localhost:8000/abc.json
validate_certs: yes
poll_interval: 10
poll_condition: '"failed" not in response.content and response.json.status=="running"'
fail_condition: '"failed" in response.content'
max_poll_attempts: 5
display_debug_msg_for_each_attempt: yes
json_query_to_build_debug_msg: "tasks[?status=='running'] | [0].name"
debug_msg_prefix: 'Prefix:'
debug_msg_suffix: ''
include_tasks: status-poller.yml
---
- set_fact:
attempts: "{{ attempts | default(0) | int + 1 }}"
- fail: msg="Number of attempts exceeded {{ max_poll_attempts }}"
when: (attempts | int) > (max_poll_attempts | int)
- debug:
msg: "Attempt: {{ attempts }}/{{ max_poll_attempts }}"
- pause:
seconds: "{{ poll_interval }}"
no_log: true
- name: Fetch status afresh
no_log: true
uri:
url: "{{ url }}"
return_content: yes
validate_certs: "{{ validate_certs }}"
register: response
failed_when: fail_condition
- debug:
msg: "{{ debug_msg_prefix | default('') }}{{ response.json | json_query(json_query_to_build_debug_msg) }}{{ debug_msg_suffix | default('') }}"
when: display_debug_msg_for_each_attempt | bool and json_query_to_build_debug_msg is defined
- include_tasks: includes/status-poller.yml
when: poll_condition
@ParagDoke
Copy link
Author

Effectively, this is equivalent of using retries and delay on the uri module. Only if there were a way to set the retry_msg (defaulting to task name and number of retries), the same could be achieved.

However, the gist may help anyone specifically looking for running multiple tasks.

@sundararajanr
Copy link

The include command is not working as expected. I have a main.yml file i want to get the list of files from the directory and pass the file name to another playbook.

@ParagDoke
Copy link
Author

The include command is not working as expected. I have a main.yml file i want to get the list of files from the directory and pass the file name to another playbook.

Share your attempt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment