name: Collect IP addresses of all target hosts set_fact: host_ip_map: "{{ host_ip_map | default({}) | combine({inventory_hostname: ansible_default_ipv4.address}) }}" delegate_to: localhost run_once: true
name: Assign IPs to specific variables set_fact: ip_vars: >- {{ dict( ('ip' ~ (index + 1), item) for index, item in host_ip_map.values()|list|slice(6)|enumerate ) }} vars: host_ip_map: "{{ hostvars | map(attribute='host_ip_map') | list | first }}" delegate_to: localhost run_once: true
name: Debug assigned variables debug: var: ip_vars
name: Use the variables randomly in subsequent tasks debug: msg: "Using IP: {{ ip_vars['ip1'] }} in this task"