with_item with none existing variable

32 views
Skip to first unread message

Christian Iuga

unread,
Mar 10, 2017, 8:38:42 AM3/10/17
to Ansible Project
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 |default 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 ?

Kai Stian Olstad

unread,
Mar 10, 2017, 9:35:41 AM3/10/17
to ansible...@googlegroups.com
On 09. mars 2017 16:45, Christian Iuga wrote:
> 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([]) }}"

--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages