variablesansibleundefined

Ansible variable undefined syntax error using set_fact


I'm getting variable is undefined error when i try 'appending' value to variable 'recdb' from another variable in set_fact.

Below is my play book:

   - name: "Collecting information"     
     shell: "ls -l {{ item }}\n\"
     register: APP
     with_fileglob:
       - "{{ playbook_dir }}/tmpfiles/*"

   - set_fact:
       fdet: "{{ APP.results|map(attribute='stdout')|list }}"

   - set_fact:
      recdb: "{{ recdb + inventory_hostname }}"

   - set_fact:
       recdb: "{{ recdb + item }}"
     loop: "{{ fdet }}" 

   - debug: msg="SOLUTION FOR TRICKY {{ recdb }}"

Expected output of recdb variable should be like below:

10.7.7.111
177    0 -rw-rw-r--  1 user1    was              0 Sep 23 10:29 /was/user1/fname1.out
177    0 -rw-rw-r--  1 user1    was              0 Sep 23 10:29 /was/user1/fname2.out
10.9.12.11
177    0 -rw-rw-r--  1 user1    was              0 Sep 23 10:29 /was/user1/fname1.out
177    0 -rw-rw-r--  1 user1    was              0 Sep 23 10:29 /was/user1/fname2.out

However, I'm getting the below error running my playbook.

fatal: [10.9.12.11]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'recdb' is undefined\n\nThe error appears to be in '/app/deploy.yml': line 942, column 6, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - set_fact:\n ^ here\n"}


Solution

  • There is no syntax error, only an undefined var.

    Your code:

    - set_fact:
        recdb: "{{ recdb + inventory_hostname }}"
    

    This is explicitely telling ansible:

    Take the current value of recdb, add (either as string or list operation, I cannot tell from your code....) the value of inventory_hostname and assign the result to the recdb var.

    In this operation, if recdb is not defined in first place, you will get an undefined var error.

    Ansible has a default filter to deal with this situation. My only problem here is to know if your are trying to concatenate two strings or to join 2 lists. So I'll give an example for both.

    concatenate strings

    - set_fact:
        my_string_var: "{{ my_string_var | default('') + my_string_var_to_concat }}"
    

    join lists

    - set_fact:
        my_list_var: "{{ my_list_var | default([]) + [my_new_value] }}"
    

    If you have several values to add at once:

    - set_fact:
        my_list_var: "{{ my_list_var | default([]) + [my_new_value1, my_new_value2, my_new_value3...] }}"