Generate An Ansible Report By Updating A Variable
by Emile `iMil' Heitor - 2022-10-29
At $(DAYJOB) I was asked to generate some kind of daily report, and I thought ansible would do the job; we basically want to have a couple of key metrics like load average, memory, disk… you see the deal. The result is to be send to MatterMost using mattermost’s ansible module.
It took me way too much time to understand how to update a single variable in order to build a mardown table that would be sent as a single request to the MatterMost server, until neith_speed told me to use hostvars
in order to have access to the data gathered by the play for every host.
Here’s the basic trick:
Initialize the output
variable by adding a table header to it, run it once, locally
- name: init output
set_fact:
output: "| hostname | load | mem | disk |\n| --- | --- | --- |"
run_once: true
delegate_to: localhost
When the facts are gathered and appended to hostvars
magic variable, get and append them to the output
variable. Do it once, by looping through ansible_play_batch
- name: build output
set_fact:
output: "{{ output | {{ item }} | {{ hostvars[item].load }} | {{ hostvars[item].mem }} | {{ hostvars[item].disk }} |\n}}"
loop: "{{ ansible_play_batch }}"
run_once: true