set_fact with_items inside var

I need to add an item to a list. This works:

  • name: “Build Pool IP List”
    set_fact:
    pool_server_ips_list: “{{pool_server_ips_list}} + [{‘ip’: {‘addr’: item, ‘type’: ‘V4’}}]”
    with_items: “{{pool_server_ips}}”

with this list:

pool_server_ips:

  • 10.8.10.4
  • 10.8.10.5
  • 10.8.10.6
  • 10.8.10.7

I need to add another element to the list so I changed it to:

pool_server_ips:

  • hostip: 10.8.10.4
    pool_member_enabled: true
  • hostip: 10.8.10.5
    pool_member_enabled: false
  • hostip: 10.8.10.6
    pool_member_enabled: false
  • hostip: 10.8.10.7

pool_member_enabled: false

then changed fact to:

set_fact:
pool_server_ips_list: “{{pool_server_ips_list}} + [{‘ip’: {‘addr’: item.hostip, ‘type’: ‘V4’}}]”
with_items: “{{pool_server_ips}}”

If I debug the list i get:

“servers”: [
+ [{‘ip’: {‘addr’: [item.hostip]”,
" ‘type’: ‘V4’}}] + [{‘ip’: {‘addr’: [item.hostip]“,
" ‘type’: ‘V4’}}] + [{‘ip’: {‘addr’: [item.hostip]”,
" ‘type’: ‘V4’}}] + [{‘ip’: {‘addr’: [item.hostip]“,
" ‘type’: ‘V4’}}]”
]

I need to add an item to a list. This works:

- name: "Build Pool IP List"
  set_fact:
    pool_server_ips_list: "{{pool_server_ips_list}} + [{'ip': {'addr':
item, 'type': 'V4'}}]"
  with_items: "{{pool_server_ips}}"

with this list:

pool_server_ips:
  - 10.8.10.4
  - 10.8.10.5
  - 10.8.10.6
  - 10.8.10.7

I need to add another element to the list so I changed it to:

pool_server_ips:
  - hostip: 10.8.10.4
    pool_member_enabled: true
  - hostip: 10.8.10.5
    pool_member_enabled: false
  - hostip: 10.8.10.6
    pool_member_enabled: false
  - hostip: 10.8.10.7
    pool_member_enabled: false

then changed fact to:

  set_fact:
     pool_server_ips_list: "{{pool_server_ips_list}} + [{'ip': {'addr':
item.hostip, 'type': 'V4'}}]"

Try:

     pool_server_ips_list: "{{pool_server_ips_list | default() + [{'ip': {'addr': item.hostip, 'type': 'V4'}}] }}"

  with_items: "{{pool_server_ips}}"

If I debug the list i get:

          "servers": [
                " + [{'ip': {'addr': [item.hostip]",
                " 'type': 'V4'}}] + [{'ip': {'addr': [item.hostip]",
                " 'type': 'V4'}}] + [{'ip': {'addr': [item.hostip]",
                " 'type': 'V4'}}] + [{'ip': {'addr': [item.hostip]",
                " 'type': 'V4'}}]"
            ]

V/r,
James Cassell

You are a champion! Thank you so much!