Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: Accumulate output across multiple hosts on task run

Tags:

ansible

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?

like image 893
Zee Avatar asked May 10 '17 21:05

Zee


People also ask

How do I run multiple tasks in Ansible?

If you need to execute a task with Ansible more than once, write a playbook and put it under source control. Then you can use the playbook to push out new configuration or confirm the configuration of remote systems.

How do I limit Ansible hosts?

Using the --limit parameter of the ansible-playbook command is the easiest option to limit the execution of the code to only one host. The advantage is that you don't need to edit the Ansible Playbook code before executing to only one host.

Which hosts are randomly ordered each run?

shuffle: Hosts are randomly ordered each run.

What is Run_once in Ansible?

Ansible run_once parameter is used with a task, which you want to run once on first host. When used, this forces the Ansible controller to attempt execution on first host in the current hosts batch, then the result can be applied to the other remaining hosts in current batch.


1 Answers

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.

like image 66
Konstantin Suvorov Avatar answered Sep 23 '22 07:09

Konstantin Suvorov