How to retry block in Ansible

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5175

    #1

    How to retry block in Ansible

    Normally you can't. But, if you really want, you can.


    Here is how.

    1. Move that block into separate tasklist. E.g. foo.yaml.
    2. import it: - import_tasks: foo.yaml.


    Now, the magic. The content of the foo.yaml






    - block:
    - set_fact:
    count: "{{ count | d(0) + 1 }}"
    - name: Arbitrary number of tasks here which can fial
    command: /bin/false
    ...
    rescue:
    - fail:
    when: count > 3
    - include_tasks: foo.yaml







    How it works.

    1. foo is run.
    2. set fact set counter to 0 (because there is no counter)
    3. your tasks run. If they finish, block finish and everything is good.
    4. If any of your task fails, rescue part will be executed. If counter is less than 3, fail is skipped and foo is included. It is the same file as you imported, this is self-recursion.
    5. Counter become + 1
    6. Try again.
      ...
    7. If count is too high, fail is executed and recursion stop.
    8. If at any count (before fail) block succeed, rescue section finishes, and recursion returns back and it continue to run as it wasn't failed at all (the desired property of the retry).


    It is terrible, but beautiful.




    More...
Working...