generate fact report with ansible

So you’ve been asked to gather a report of several metrics of some servers you manage. It needs to be readable, so tabular output would be best. What can we do with ansible?

Well, we can leverage facts to get the data we desire, and then output them locally to a template csv.

Create a local jinja2 csv template file with the fields desired. In my case, we’ll be gathering mostly hardware specific information:

servers.csv.j2:

hostname,system_vendor,product_name,platform,memory(mb),number_of_cpus
{% for h in ansible_play_hosts %}
{{ h }},{{ hostvars[h]['ansible_system_vendor'] }},{{ hostvars[h]['ansible_product_name'] }},{{ hostvars[h]['ansible_distribution'] }} {{ hostvars[h]['ansible_distribution_version'] }},{{ hostvars[h]['ansible_memtotal_mb'] }},{{ hostvars[h]['ansible_processor_vcpus'] }}
{% endfor %}

Now, we’ll form our playbook as such:

playbook.yml:

- hosts: all
  become: yes
  gather_facts: yes

  tasks:
    - name: output to template
      template:
        src: servers.csv.j2
        dest: servers.csv
      delegate_to: localhost

Note: This example will require you to have the same credentials locally as well as remotely. If your user account locally differs from your remote account used for fact gathering, you’ll need to play around with your ansible.cfg and likely ansible-vault along with inventory variables to manage separate passwords.

Here’s an example of the resulting local servers.csv file:

hostname,system_vendor,product_name,platform,memory(mb),number_of_cpus
server1,QEMU,Standard PC (Q35 + ICH9, 2009),CentOS 9,3719,2
server2,QEMU,Standard PC (Q35 + ICH9, 2009),CentOS 9,7125,4