当未定义变量时跳过Ansible任务

时间:2016-11-04 14:15:09

标签: ansible

我在剧本中有以下任务:

- name: task xyz  
  copy:  
    src="{{ item }}"  
    dest="/tmp/{{ item }}"  
  with_items: "{{ y.z }}"  
  when: y.z is defined  

y.z未定义,因此我希望跳过该任务。相反,我收到:

FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'z'"

我发现: How to run a task when variable is undefined in ansible? 但似乎我实现了这一点。我在这里做错了什么?

1 个答案:

答案 0 :(得分:7)

这里的问题是在with_items之前评估when。实际上,在实际场景中,您将item置于when条件中。请参阅:Loops and Conditionals

此任务适合您:

- name: task xyz
  copy:  
    src: "{{ item }}"  
    dest: "/tmp/{{ item }}"  
  with_items: "{{ (y|default([])).z | default([]) }}"
相关问题