How to access stdout from all hosts in a localserver

My playbook is as follows

  • hosts: nodes
    become: yes
    tasks:
  • name: Run Shell Script to get IPs with 4xx and 5xx errors

script: /home/ubuntu/ips.sh
args:
chdir: /home/ubuntu
register: ips

  • name:
    shell: echo “{{ hostvars[groups[‘nodes’][0]].ips.stdout}}” > pip.txt
    delegate_to: localhost

There are 10 ansible hosts. Is There a way I can access Ips.stdout from all 10 hosts from my local server. I’m able to get the first host by the above command. How can I access all 10 hosts stdout from a single variable?

My playbook is as follows

- hosts: nodes
  become: yes
  tasks:
  - name: Run Shell Script to get IPs with 4xx and 5xx errors

    script: /home/ubuntu/ips.sh
    args:
      chdir: /home/ubuntu
    register: ips

  - name:
    shell: echo "{{ hostvars[groups['nodes'][0]].ips.stdout}}" > pip.txt
    delegate_to: localhost

Running shell like this will run the task as many times as it's hosts in nodes.
Each one will overwrite the pip.txt file.

There are 10 ansible hosts. Is There a way I can access Ips.stdout from all
10 hosts from my local server. I'm able to get the first host by the above
command. How can I access all 10 hosts stdout from a single variable?

You can use a loop with with_items like this

- debug: msg="{{ item.ips.stdout }}"
  with_items: "{{ groups.nodes }}"
  delegate_to: localhost

(just for the record, debug module always run on localhost, so with debug delegate_to could be left out)

But still this task will still run as many times as there are hosts in nodes.
To mitigate that you have "run_once: true" that only run this task one time.

- debug: msg="{{ item.ips.stdout }}"
  with_items: "{{ group.nodes }}"
  delegate_to: localhost
  run_once: true

But since you would like to have this in a file you would need to use Jinja template and the copy module.
So instead of looping with with_items you do the loop in Jinga template.

- copy:
    content: |
      {% for host in groups.nodes %}
      {{ hostvars[host].ips.stdout }}
      {% endfor %}}
    dest: /tmp/pip.txt
  delegate_to: localhost
  run_once: true