Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop with conditional statement

Tags:

ansible

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
like image 208
shawlin Avatar asked May 15 '26 10:05

shawlin


1 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 != ''"
like image 56
β.εηοιτ.βε Avatar answered May 17 '26 03:05

β.εηοιτ.βε



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!