Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check the defined variable is empty or not in Ansible

Tags:

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]: FAILED! => {<br>
    "msg": "Unexpected failure during module execution.", <br>
    "stdout": ""<br>
}

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

like image 938
shreyash Avatar asked Sep 14 '25 00:09

shreyash


2 Answers

Q: "Check whether 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.


Notes

  1. The evaluation of 'not item' works in the context of this question if the variable is a string, list, dictionary, or None. if the variable is a boolean or number this test does not work. See the self-explaining test below
    - debug:
        msg: "{{ not item }}"
      loop:
        - ''
        - []
        - {}
        -
        - null
        - true
        - false
        - 1
        - 0

gives

TASK [debug] **************************************************
ok: [localhost] => (item=) => 
  msg: true
ok: [localhost] => (item=[]) => 
  msg: true
ok: [localhost] => (item={}) => 
  msg: true
ok: [localhost] => (item=None) => 
  msg: true
ok: [localhost] => (item=None) => 
  msg: true
ok: [localhost] => (item=True) => 
  msg: false
ok: [localhost] => (item=False) => 
  msg: true
ok: [localhost] => (item=1) => 
  msg: false
ok: [localhost] => (item=0) => 
  msg: true
  1. To fix this problem test the variable is iterable
    - debug:
        msg: "{{ item is iterable }}"
      loop:
        - ''
        - []
        - {}
        -
        - null
        - false
        - 0

gives

TASK [debug] ******************************************************
ok: [localhost] => (item=) => 
  msg: true
ok: [localhost] => (item=[]) => 
  msg: true
ok: [localhost] => (item={}) => 
  msg: true
ok: [localhost] => (item=None) => 
  msg: false
ok: [localhost] => (item=None) => 
  msg: false
ok: [localhost] => (item=False) => 
  msg: false
ok: [localhost] => (item=0) => 
  msg: false

Complete test: The variable is empty or None

    - debug:
        msg: The variable is empty or None.
      when:
        - not item
        - item is iterable or item is none
      loop:
        - ''
        - []
        - {}
        -
        - null
        - true
        - false
        - 1
        - 0

gives

TASK [debug] ***************************************************
ok: [localhost] => (item=) => 
  msg: The variable is empty or None.
ok: [localhost] => (item=[]) => 
  msg: The variable is empty or None.
ok: [localhost] => (item={}) => 
  msg: The variable is empty or None.
ok: [localhost] => (item=None) => 
  msg: The variable is empty or None.
ok: [localhost] => (item=None) => 
  msg: The variable is empty or None.
skipping: [localhost] => (item=True) 
skipping: [localhost] => (item=False) 
skipping: [localhost] => (item=1) 
skipping: [localhost] => (item=0)
  1. A dictionary is also iterable. A list of the keys is used
    - debug:
        var: item
      loop: "{{ files|list }}"
      vars:
        files:
          a: 1
          b: 2
          c: 3

gives

TASK [debug] ********************************************************
ok: [localhost] => (item=a) => 
  ansible_loop_var: item
  item: a
ok: [localhost] => (item=b) => 
  ansible_loop_var: item
  item: b
ok: [localhost] => (item=c) => 
  ansible_loop_var: item
  item: c
like image 119
Vladimir Botka Avatar answered Sep 17 '25 12:09

Vladimir Botka


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 == "")

like image 38
Smily Avatar answered Sep 17 '25 10:09

Smily