Skip Ansible task when variable not defined

2019-02-20 07:31发布

问题:

I have the following task in a playbook:

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

y.z is not defined, so I'm expecting the task to be skipped. Instead, I receive:

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

I have found: How to run a task when variable is undefined in ansible? but it seems I implemented just that. What am I doing wrong here?

回答1:

The problem here is that with_items is evaluated before when. Actually in real scenarios you put item in the when conditional. See: Loops and Conditionals.

This task will work for you:

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


标签: ansible