shawlin
shawlin

Reputation: 133

Loop with conditional statement

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

Upvotes: 8

Views: 16961

Answers (2)

U880D
U880D

Reputation: 12027

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

Upvotes: 4

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39099

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 != ''"

Upvotes: 11

Related Questions