sebelk
sebelk

Reputation: 644

How to get ansible results of a loop even if a item failed?

I have the following playbook that checks if a http redirect is performed:

---
- hosts: localhost
  tasks:
    - name: Check http redirect
      uri:
        url: "{{item}}"
        method: GET
      loop:
        - http://www.stackoverflow.com
        - http://www.twitter.com
        - http://www.example.com
      register: result
      failed_when: result.redirected is false

    - name: Print return information from the previous task
      ansible.builtin.debug:
        var: result.results[{{index}}].url
      loop:
        - http://www.stackoverflow.com
        - http://www.twitter.com
        - http://www.example.com
      loop_control:
        index_var: index

The problem is if even only one of the items fails, the second task is not executed at all.

What I expects is something like this:

TASK [Print return information from the previous task] *****************************************************************************
ok: [localhost] => (item=http://www.stackoverflow.com) => {
    "ansible_index_var": "index",
    "ansible_loop_var": "item",
    "index": 0,
    "item": "http://www.stackoverflow.com",
    "result.results[0].url": "https://stackoverflow.com/"
}
ok: [localhost] => (item=http://www.twitter.com) => {
    "ansible_index_var": "index",
    "ansible_loop_var": "item",
    "index": 1,
    "item": "http://www.twitter.com",
    "result.results[1].url": "https://twitter.com/"
}
failed: [localhost] => (item=http://www.example.com) => {
    "ansible_index_var": "index",
    "ansible_loop_var": "item",
    "index": 1,
    "item": "http://www.example.com",
    "result.results[2].url": NULL
}

How can I get the url that successfully get redirected?

EDIT 1

I've found a way to do it that is appending the line:

ignore_errors: true

after line

failed_when: result.redirected is false

Upvotes: 0

Views: 1735

Answers (1)

Derple
Derple

Reputation: 863

From the Documentation https://docs.ansible.com/ansible/latest/user_guide/playbooks_blocks.html

By using exceptions the code will continue if you give a way for the fail to succeed.

- block:
    - debug:
        msg: "This is a basic task that will run in the block"
  rescue:
    - debug:
        msg: "This task will only run if something fails in the main block
  always:
    - debug:
        msg: "This task always runs, irrespective of whether the tasks in the main block succeed or not"

Upvotes: 1

Related Questions