Ansible: Accumulate output across multiple hosts on task run
Asked Answered
A

2

12

I have the following playbook

- hosts: all
  gather_facts: False
  tasks:
    - name: Check status of applications
      shell: somecommand
      register: result
      changed_when: False
      always_run: yes

After this task, I want to run a mail task that will mail the accumulated output of all the commands for the above task registered in the variable result. As of right now, when I try and do this, I get mailed for every single host. Is there some way to accumulate the output across multiple hosts and register that to a variable?

Aguascalientes answered 10/5, 2017 at 21:37 Comment(0)
P
24

You can extract result from hostvars inside a run_once task:

- hosts: mygroup
  gather_facts: false
  tasks:
    - shell: date
      register: date_res
      changed_when: false
    - debug:
        msg: "{{ ansible_play_hosts | map('extract', hostvars, 'date_res') | map(attribute='stdout') | list }}"
      run_once: yes

This will print out a list of all date_res.stdout from all hosts in the current play and run this task only once.

Polymerize answered 11/5, 2017 at 7:0 Comment(2)
run_once runs on the first host right? How does this get the variables from every host if the debug part is run on the first host not the last?Radcliff
The default strategy for task execution is the linear strategy, each task is run on every host before moving on to the next host.Footed
A
0

While trying to copy the results of date_res.stdout to a file on host only single host data is copied not the all host's data is available

  - name: copy all 
    copy:
      content: "{{ allhost_out.stdout }}"
      dest: "/ngs/app/user/outputsecond-{{ inventory_hostname }}.txt"
Apollo answered 26/9, 2022 at 14:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.