This works for me:
---
- hosts: localhost
connection: local
gather_facts: false
vars:
interfaces:
- name: lo0
unit0:
ip_primary: 1.1.1.1
ip_secondary: 2.2.2.2
unit1:
ip_primary: 3.3.3.3
ip_secondary: 4.4.4.4
- name: xyz
unit0:
ip_primary: 9.9.9.9
tasks:
- set_fact:
myip: |
{%- set ips = [] -%}
{%- do ips.append(interface.unit0.ip_primary) -%}
{%- endfor -%}
{{ ips }}
- debug: var=myip
$ ansible-playbook -i local test101.yml
PLAY [localhost] **************************************************************
TASK: [set_fact ] *************************************************************
ok: [localhost]
TASK: [debug var=myip] ********************************************************
ok: [localhost] => {
"var": {
"myip": [
"1.1.1.1"
]
}
}
PLAY RECAP ********************************************************************
set_fact --------------------------------------------------------------- 0.04s
debug var=myip ---------------------------------------------------------- 0.00s
localhost : ok=2 changed=0 unreachable=0 failed=0