Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip certain items on condition in ansible with_items loop

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.

like image 239
m_messiah Avatar asked May 12 '16 14:05

m_messiah


People also ask

What is {{ item }} Ansible?

item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops. In the following example: - debug: msg: "{{ item }}" with_items: - first - second. the task will be run twice: first time with the variable item set to first , the second time with second .

What is the difference between loop and With_items in Ansible?

Ansible documentation recommend user to use or replace with_items with loop. So, with_items is the older way of writing Ansible playbooks and loop is the newer way of writing the playbook. For most part they are almost identical.

How do you use nested loops in Ansible?

Nested loops in many ways are similar in nature to a set of arrays that would be iterated over using the with_nested operator. Nested loops provide us with a succinct way of iterating over multiple lists within a single task. Now we can create nested loops using with_nested.


1 Answers

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
like image 154
Petro026 Avatar answered Sep 22 '22 04:09

Petro026