9

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
β.εηοιτ.βε
40.2k14 gold badges81 silver badges104 bronze badges
asked Mar 26, 2022 at 15:47

2 Answers 2

12

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 != ''"
answered Mar 26, 2022 at 18:59
Sign up to request clarification or add additional context in comments.

Comments

4

Regarding

Is it possible to have loop with conditional statement in Ansible?

sure, according Loops

When combining conditionals with a loop, the when: statement is processed separately for each item. See Basic conditionals with when for examples.

Further Q&A

answered Mar 26, 2022 at 16:46

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.