2016-05-12 53 views

回答

8

對方回答是接近,但會跳過所有項目= 2。我不認爲這是你想要的!這裏就是我會做:

- 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 
1

對每個項目評估有關任務的when:條件。因此,在這種情況下,你可以做:

... 
with_items: 
- 1 
- 2 
- 3 
when: item != 2 and test_var is defined 
+1

你可能想'when:(item == 2 and test_var defined)或item!= 2';或者它永遠不會執行其他項目 –

+0

好的一點 - 這就是我得到的快速解決這個問題的方法。 ;) – nitzmahone

+0

你只需要將'和'換成'或'? –

0

你想要的是該文件1和文件3總是被創建,但文件2只有當test_var定義創建。如果您使用ansible的條件時,它的工作原理上完成任務,而不是單個項目是這樣的:

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

此任務將檢查車況的所有三個行項目1,2和3

但是你可以通過兩個簡單的任務來達到這個目的:

- name: test task 
    command: touch "{{ item }}" 
    with_items: 
     - 1 
     - 3 

- name: test task 
    command: touch "{{ item }}" 
    with_items: 
     - 2 
    when: test_var is defined 
+0

你的陳述「當條件在完成任務而不是在單個項目上工作時是不可能的」是錯誤的:對每個項目單獨評估條件。看到http://docs.ansible.com/ansible/playbooks_conditionals.html#loops-and-conditionals –

+0

你讓我錯了,我自己也說同樣的事情你在說什麼。在我的回答中看到,我還提到了這個「這項任務將檢查所有三個行項目1,2和3的條件」。通過上面的陳述,我的意思是說,當條件不僅適用於一個項目,而且適用於所有這意味着整個任務。 –