Piascwal
Piascwal

Reputation: 23

Ansible - Try to get a file on multiple url and fail only if all url have been called and file has not been found

I have a file that could be located on 1 of 3 urls, but not in the two others

I would like to try to get the file on each url:

I have tried this :

  - name : Try to get the file
    uri:
      url: "{{ item }}"
      return_content: yes
      status_code:
        - 200
        - 404
    register: module_result
    with_items:
      - http://url_1/file.txt
      - http://url_2/file.txt
      - http://url_3/file.txt
    when: module_result is not defined or module_result.status == 404

But there is some not handled cases:

So my questions are :

Thank you

Upvotes: 0

Views: 864

Answers (1)

Grzegorz Pudłowski
Grzegorz Pudłowski

Reputation: 537

Try this:

- name: Try to get the file
  uri:
    url: "{{ item }}"
    return_content: yes
  register: module_result
  with_items:
    - http://url_1/file.txt
    - http://url_2/file.txt
    - http://url_3/file.txt
  ignore_errors: yes

- name: Register if there was any 200 status code
  set_fact:
    existing_file: "{{ item }}"
  with_items: "{{ module_result.results }}"
  when: item.status is defined and item.status == 200

- name: Fail if no 200 status code received
  fail:
    msg: No such file
  when: existing_file is not defined

- name: Display file content
  debug:
    msg: "{{ existing_file.content }}"
  1. Loop over all URLs without failing at all
  2. Loop over results and set existing_file variable only if result with 200 status code was found
  3. Fail if existing_file is not defined
  4. If not failed then your file content is in existing_file.content (and in this example will be displayed with debug)

Upvotes: 2

Related Questions