Skip certain items on condition in ansible with_items loop

m_messiah picture m_messiah · May 12, 2016 · Viewed 23.7k times · Source

Is it possible to skip some items in Ansible with_items loop operator, on a conditional, without generating an additional step?

Just for example:

- name: test task
    command: touch "{{ item.item }}"
    with_items:
      - { item: "1" }
      - { item: "2", when: "test_var is defined" }
      - { item: "3" }

in this task I want to create file 2 only when test_var is defined.

Answer

Petro026 picture Petro026 · May 12, 2016

The other answer is close but will skip all items != 2. I don't think that's what you want. here's what I would do:

- hosts: localhost
  tasks:
  - debug: msg="touch {{item.id}}"
    with_items:
    - { id: 1 }
    - { id: 2 , create: "{{ test_var is defined }}" }
    - { id: 3 }
    when: item.create | default(True) | bool