with_item with none existing variable

Hi,

I’m trying to deal with non existing variable when i use --tags (so lot of task are skipped)

I have read many time the “http://docs.ansible.com/ansible/playbooks_conditionals.html#loops-and-conditionals”, specially this part :
If you need to skip the whole task depending on the loop variable being defined, used the filter to provide an empty iterator:

- command: echo {{ item }}
  with_items: "{{ mylist|default([]) }}"
  when: item > 5

On my site.yml, i load several (if exist) several task on pre_tasks (so before roles):
hosts: all
pre_tasks:

  • name : check if need to load custom task
    local_action: stat path=“tasks/{{ item }}.yml”
    with_items:
  • “{{ group_names }}”
    become: no
    register: file
  • name : “Loading custome task with {{ group_names }}”
    include: “{{ item.stat.path }}”
    when: “{{ item.stat.exists }}”
    with_items: “{{ file.results }}”

normaly, It’s working great but if i skip this part (via --tags) it’s failed with :
‘file’ is undefined

i don’t known how to try write my with_items condition :

with_items: “{{ file|default() }}” : is skipping but not work on normal condition (without the --tags )
with_items: “{{ file|default().results }}” : template error while templating string
with_items: "{{ file.results|default() }} : ‘file’ is undefined

Do you have a idea how to deal with this kind of problem ?

You need to filter file and file.results through the default filter.

with_items: "{{ (file | default()).results | default() }}"