Ansible loop with conditional statement

Viewed 1298

Is it possible to have loop with conditional statement in Ansible? What I want is to find whether a path exists for a specific file. If it exists, to perform a loop, and only for that specific file to see conditional statement. Code sample below

  - name: File exist
    stat:
      path: <path to the file or directory you want to check>
    register: register_name

- name: Copy file
  copy:
    src: '{{ item }}'
    dest: '<destination path>'
  with_fileglob:
    - ../spring.jar
    - <perform if statement. if register_name.stat.exists, ../info.txt, else dont copy this info.txt >


# ... few other task with loop instead of with_fileglob
2 Answers

You can and the pseudo code you are providing is close to a solution that would work.

There is an inline if expression that can make you act on the items of the list.
From there on, you could make an empty string if the file your where expecting does not exist — because, sadly, you cannot omit an element of a list.

Because a copy with an empty element will make it fail, you now have two options, either filter the list to remove empty elements or make a condition with a when to skip them.

Here would be the solution filtering empty elements, with the select filter:

- copy:
    src: "{{ item }}"
    dest: /tmp
  loop: "{{ _loop | select }}"
  vars:
    _loop:
      - ../spring.jar
      - "{{ '../info.txt' if register_name.stat.exists else '' }}"

And here is the solution using a condition:

- copy:
    src: "{{ item }}"
    dest: /tmp
  loop:
    - ../spring.jar
    - "{{ '../info.txt' if register_name.stat.exists else '' }}"
  when: "item != ''"
Related