Skip to content

Instantly share code, notes, and snippets.

@webkonstantin
Forked from ParagDoke/main.yml
Created December 28, 2018 18:32
Show Gist options
  • Save webkonstantin/a88a687b430bfb1d8780d0aa6c694087 to your computer and use it in GitHub Desktop.
Save webkonstantin/a88a687b430bfb1d8780d0aa6c694087 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment