set_fact doesn't work in loop

19 views
Skip to first unread message

Jason Crabtree

unread,
Oct 11, 2019, 4:23:54 PM10/11/19
to Ansible Project
Hello,

I'm trying to build a list from data in other lists by looping over lists and using set_fact to build a new list. 

----------------------------------------------
- name: "test list build"
  hosts: localhost
  connection: local
  gather_facts: no
  become: no


  vars:
    location_list:
      site:
        - portland
        - miami
        - chicago
    item_list:
      - nowhere



  tasks:

    - name: "create list"
      set_fact:
        item_list: '{{ item_list +  [ "{{ item }}" ]  }}'
      loop: "{{ location_list.site }}"

     
    - name: "display final item_list"
      debug:
        msg: "{{ item_list }}"

----------------------------------------------

I expected the list:
nowhere
portland
miami
chicago

I got:
nowhere
miami
{{ item }}
{{ item }}

Can anyone point out what I got wrong or is this just a bug?

Thanks,

Kai Stian Olstad

unread,
Oct 11, 2019, 5:36:29 PM10/11/19
to ansible...@googlegroups.com
On 11.10.2019 22:23, Jason Crabtree wrote:
> Hello,
>
> I'm trying to build a list from data in other lists by looping over
> lists
> and using set_fact to build a new list.
>
> ----------------------------------------------
> - name: "test list build"
> hosts: localhost
> connection: local
> gather_facts: no
> become: no
>
>
> vars:
> location_list:
> site:
> - portland
> - miami
> - chicago
> item_list:
> - nowhere
>
>
>
> tasks:
>
> - name: "create list"
> set_fact:
> item_list: '{{ item_list + [ "{{ item }}" ] }}'
> loop: "{{ location_list.site }}"

You can't use {{ }} inside {{ }} since you are already in template mode.
So use this instead

item_list: '{{ item_list + [ item ] }}'


But you can solve this a lot faster without a loop with the union filter

- name: "create list"
set_fact:
item_list: '{{ item_list | union(location_list.site) }}'


--
Kai Stian Olstad

Jason Crabtree

unread,
Oct 11, 2019, 5:48:21 PM10/11/19
to Ansible Project
Thank you. I'll try the update in my actual script and see how it goes.

I can't do a join since it's not a simple list I'm really trying to turn into a simple list. This code seemed to demonstrate the crux of my issue though and I'm hoping you provided the solution I needed.

I'm still trying to understand when  quotes and brackets should be used.

-Jason
Reply all
Reply to author
Forward
0 new messages