Register variable in task with loop and use registered results for task conditional

159 views
Skip to first unread message

tterr...@gmail.com

unread,
Mar 29, 2021, 4:54:59 AM3/29/21
to Ansible Project
I am trying to run a loop over a task and I am registering the results. The items in the loop are not unique and can repeat. I don't want to run the same item twice. So, in the same task, I want to use a conditional to check if the current loop item has run so far in the loop. For this, I use the registered variable and using some filters, I try to extract the items that were not skipped so far. (I know I could use the `unique` filter for the use case above. But this is a trimmed down version of the actual use case where each loop item is a list where the first item can be common among different loop items, `apply: tags` is used, etc).

In the example below, instead of `skipped` I use `failed` to keep the example simple.

- hosts:
    - localhost
gather_facts: no
tasks:
  - debug: msg=item
    loop: [1,2,3,1,2,3,4,5]
    loop_control:
      index_var: index
    failed_when: index == 3
    register: r
    ignore_errors: true
    when:
      - 'item not in r.results | d([]) | reject("failed") | map(attribute="item") | flatten'
   - debug:
     msg: "{{ r.results | d([]) | reject('failed') | map(attribute='item') | flatten }}"

I know this example could be rewritten with `until`, I just constructed it to demonstrate my point.

The first tasks prints all loop items. The second one shows however that item number 3 was failed.

Is there a way to access the results from previous loop items somehow? Is this sth I should request on github from the ansible team?
Reply all
Reply to author
Forward
0 new messages