'Check the defined variable is empty or not in Ansible

- hosts: localhost
  vars:
           files_list:
           #it may contain the file_list like 
           #file_list: 
           #     - "file*"
  tasks: 
       - name: copy
         copy:
             src: "{{item}}"
             dest: "/tmp/"
         with_fileglob: "{{files_list}}"
         when: files != None

I want to copy some multiple files with a specific pattern from the files_list. but sometimes the file_list may be empty. so how to check if the file_list is empty I have tried above code but it doesn't work. it is giving me following error

The full traceback is:<br>
Traceback (most recent call last):<br>
  File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 104, in run<br>
    items = self._get_loop_items()<br>
  File "/usr/lib/python2.7/site-packages/ansible/executor/task_executor.py", line 245, in _get_loop_items<br>
    items = wrap_var(mylookup.run(terms=loop_terms, variables=self._job_vars, wantlist=True))<br>
  File "/usr/lib/python2.7/site-packages/ansible/plugins/lookup/fileglob.py", line 60, in run<br>
    term_file = os.path.basename(term)<br>
  File "/usr/lib64/python2.7/posixpath.py", line 121, in basename<br>
    i = p.rfind('/') + 1<br>
AttributeError: 'NoneType' object has no attribute 'rfind'<br>
fatal: [machine1.kirusa.com]: FAILED! => {<br>
    "msg": "Unexpected failure during module execution.", <br>
    "stdout": ""<br>
}

Can you also explain whats this mean. thank you in advance.



Solution 1:[1]

Q: "Check the defined variable is empty or not in Ansible."

A: Simply test the variable. An empty list evaluates to False. This also covers the case when the variable is not defined. YAML None is Python null. None also evaluates to False. For example

- debug:
    msg: The variable files is an empty list or None.
  when: not files|default(None)
  • In the loop, it's not necessary to test whether the list is empty or not. An empty list will be skipped anyway.

  • YAML string is a list of characters. An empty string evaluates to False the same way as an empty list does.

Solution 2:[2]

To check if it is empty you need to give as below

when: not files_list

See Default rules here: https://docs.ansible.com/ansible-lint/rules/default_rules.html

It states: Don’t compare to empty string, use when: var rather than when: var != "" (or conversely when: not var rather than when: var == "")

Solution 3:[3]

You can first assert that it is indeed a list and then assert that it has more than one element:

when: (files_list is defined) and (files_list | type_debug == 'list') and (files_list | count > 0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 stackprotector