Skip to content

Instantly share code, notes, and snippets.

@cidrblock
Created October 6, 2021 21:17
Show Gist options
  • Select an option

  • Save cidrblock/e78cc5051bcb629314fbe4c28a0787d2 to your computer and use it in GitHub Desktop.

Select an option

Save cidrblock/e78cc5051bcb629314fbe4c28a0787d2 to your computer and use it in GitHub Desktop.
- name: Generate a random number
ansible.builtin.set_fact:
num: "{{ pick_from | random(start=1) }}"
- name: Set the condition flag
ansible.builtin.set_fact:
condition_met: "{{ num|int == number_to_match }}"
- name: Get out quick when condition is met
ansible.builtin.fail:
when: condition_met
- hosts: localhost
gather_facts: False
vars:
condition_met: False
max_iterations: 10
number_to_match: 5
pick_from: 20
tasks:
- block:
- ansible.builtin.include_tasks:
file: random_number.yaml
loop: "{{ range(0, max_iterations, 1) }}"
- name: Fail if the condition isn't met
ansible.builtin.fail:
msg: "max iterations completed"
when: not condition_met
rescue:
- debug:
msg: "Sorry, after {{ max_iterations }} attempts, num was {{ num }}"
when: not condition_met
failed_when: not condition_met
- debug:
msg: "We survived, num was {{ num }}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment