Ansible Generate CSV report from Multiple Facts

Viewed 316

I hope this finds you all well.

I´m struggling to generate a CSV from multiple facts corresponding to the same hosts.

More specifically, I have the following facts:

   ntp_status:
    host01: Clock is synchronized
    host02: Clock is synchronized
    host03: Clock is not synchronized

   ping_status:
    host01: Ping success
    host02: Ping not success
    host03: Ping success

The idea is to have a report in a CSV file report.csv, hence I would expect to generate with Jinja something like the following:

   host, ntp_status, ping_status
   host01, Clock is synchronized, Ping success
   host02, Clock is synchronized, Ping not success
   host03, Clock is not synchronized, Ping success

I hope you can help me with this. Thank you in advance

1 Answers

For example

    - debug:
        msg: |
          host, ntp_status, ping_status
          {% for i in _csv %}
          {{ i }}
          {% endfor %}
      vars:
        _hosts: "{{ ntp_status.keys()|list }}"
        _ntp: "{{ ntp_status.values()|list }}"
        _ping: "{{ ping_status.values()|list }}"
        _csv: "{{ _hosts|zip(_ntp)|zip(_ping)|
                  map('flatten')|
                  map('join', ', ')|list }}"

gives

  msg: |-
    host, ntp_status, ping_status
    host01, Clock is synchronized, Ping success
    host02, Clock is synchronized, Ping not success
    host03, Clock is not synchronized, Ping success

The next option is to create the structure in the template. The task below gives the same result

    - debug:
        msg: |
          host, ntp_status, ping_status
          {% for i in _hosts %}
          {{ i }}, {{ ntp_status[i] }}, {{ ping_status[i] }}
          {% endfor %}
      vars:
        _hosts: "{{ ntp_status.keys()|list }}"

Put the template into a file, e.g.

shell> cat report.csv.j2 
host, ntp_status, ping_status
{% for i in _hosts %}
{{ i }}, {{ ntp_status[i] }}, {{ ping_status[i] }}
{% endfor %}

and create the report

    - template:
        src: report.csv.j2
        dest: report.csv
      vars:
        _hosts: "{{ ntp_status.keys()|list }}"

gives

shell> cat report.csv
host, ntp_status, ping_status
host01, Clock is synchronized, Ping success
host02, Clock is synchronized, Ping not success
host03, Clock is not synchronized, Ping success
Related