How to access stdout from all hosts in a localserver

35 views
Skip to first unread message

Leela Sai Madhav Manne

unread,
Dec 25, 2018, 11:10:57 PM12/25/18
to Ansible Project
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?

Kai Stian Olstad

unread,
Dec 26, 2018, 5:14:19 AM12/26/18
to ansible...@googlegroups.com
On Wednesday, 26 December 2018 05:10:57 CET Leela Sai Madhav Manne wrote:
> 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


--
Kai Stian Olstad


Reply all
Reply to author
Forward
0 new messages