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

2,941 views
Skip to first unread message

Ritesh Sharma

unread,
Jan 5, 2017, 11:14:28 AM1/5/17
to Ansible Project
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 .  

 

Brian Coca

unread,
Jan 5, 2017, 11:29:13 AM1/5/17
to ansible...@googlegroups.com
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)}"



----------
Brian Coca

Ritesh Sharma

unread,
Jan 10, 2017, 1:57:01 PM1/10/17
to Ansible Project
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, 

Brian Coca

unread,
Jan 10, 2017, 2:06:39 PM1/10/17
to ansible...@googlegroups.com
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.

 set_fact: myvar="{{
​path|map('
dirname
​')|list​
}}"

----------
Brian Coca

Ritesh Sharma

unread,
Jan 12, 2017, 2:17:09 AM1/12/17
to Ansible Project
Ok Thanks Brian . 
Reply all
Reply to author
Forward
0 new messages