I’m relatively new to Ansible. I’m looking for a pattern for gathering some custom, dynamic facts from hosts and then processing them locally. For instance, can anyone point me to an example of a simple play that runs df(1), calculates the total disk used, and prints the df output and the total for all the hosts? That example would get me started in the direction I want to go.
The script I’m running on my hosts returns multiple lines of output, I want to gather that output and display it. The last line of the output is a number. I want to add up all those values and have the play print the total at the end of the play.
Googling ansible calculate total disk usage did not return helpful results.
Or is my problem that Ansible isn’t designed for such things. I know I can run the play from a local wrapper script and then post-process the JSON to my heart’s content. I was hoping to do this all native inside Ansible, though.
If you're literally looking for total disk used, that comes in the
default ansible facts- try running this against a host or two:
I think I understand how facts work and how your example will give me disk space per host. My problem is how to then add up those host-specific numbers into a single number for the entire play.
I think the answer to my question, reinforced by advice from a work colleague, is that Ansible is the right tool for performing tasks on multiple hosts, but there’s no way in a playbook to manipulate host results to make calculations across hosts. Today I’m tackling this with the API in a Python script.
This isn't true- using the `hostvars` dictionary (keyed by inventory
names), you can look at arbitrary values for arbitrary hosts. There's
also a globally available 'groups' dictionary (the values are lists of
hosts) if you want to sort and categorize.
Seriously, try a callback plugin. You can then make sure you get
updated information after all provisioning runs, instead of requiring
a separate step.
Thanks for bearing with me. I see what you mean now and am studying callbacks.