Create a new list after setting fact

I have a playbook that looks like this

   ---
   - hosts: localhost
     gather_facts: false
     connection: local

     vars: 
       addresses: ['10.10.10.0/28', '10.11.11.0/28']
       list_address: []

     tasks:

       - name: set empty list for cidr
         set_fact:
           ips_and_masks: []

       - name: set up address fact
         set_fact:
           address: "{{ item.split('/')[0] }} {{ item | ipaddr('netmask') }}"
         loop: "{{ item.addresses }}"

       - name: create new list
         set_fact:
           list_address: "{{ list_address + [address] }}"
    
       - name: debug new list
         debug:
            msg: "Addresses: {{ list_address }}"

I'm trying to get the output to be

"Address": [
    "10.10.10.0 255.255.255.240",
    "10.11.11.0 255.255.255.240"
]

But the second iteration of the loop overwrites the first so I end up with

"Address": [
    "10.11.11.0 255.255.255.240"
]

Is there a way to append it rather than overwrite it?

1 answer

  • answered 2020-11-20 11:21 Héctor

    You don't need address fact at all. Change your task to this:

    - name: set up address fact
      set_fact:
        list_address: "{{ (list_address | default([])) + [ (item.split('/')[0]) + (item | ipaddr('netmask')) ] }}"
      loop: "{{ addresses }}"
    

    Then, you can remove create new list task.

    You can remove list_address var declaration as well, because it's been initialized in set_fact (as @Zeitounator says in comments)