Initializing "List" with dynamic values through "with_items" is not working .

Hi Guys ,

i am attempting to initialise list (array) with set_fact method with some dynamic values through with_items ; but getting failure for same ; it seems like my list is acting as a normal variable and printing the last value assigned to it.

here’s the playbook for same .

---
- hosts: wallet
  tasks:
    - name: Verifying existence of stat directory
      file: path=/tmp/ansibleTest  state=directory

    - name: Identify current logging directory 
      find: paths="/tmp/ansibleTest/perf_output" file_type="directory" age="-2m" recurse="yes" age_stamp="mtime"
      register: result

    - debug: var=result

    - set_fact: path="{{item.path}}"
      with_items: "{{result.files}}"   
   - debug: var=path 
path is acting as a normal variable and priniting last value assigned to it through - with_items: "{{result.files}}" ; I am expecting list of values contained by result.files[]
Kindly, reply what exactly i am doing incorrectly.

Kind Regards,
Ritesh .  

 

In this case you are setting path to each item path on every loop, not appending as set_fact is not capable of this.

What you want is a map:

set_fact: path=“{{result.files|map(attribute=‘path’)|list)}”

Hey Brian ,

Thanks for help it worked like a charm ; now am trying to process these array elements with “dirname” filter in loop but unable to do so,

  • set_fact: path=“{{result.files|map(attribute=‘path’)|list)}”

  • set_fact: myvar=“{{ item | dirname }}”
    with_item: “{{path}}”

  • debug: var=myvar

“dirname” is working but only for the last element of array , kindly Help !!

P.S. : I am new to ansible , could you please share some links ,doc which can help me to get through such issues .

Kind Regards,

Several issues, missing an S, also your indentation seems off.

with_items: “{{path}}”

But also, set_fact is overwriting myvar FOR each item, not creating a list, you want to use map again.

Ok Thanks Brian .