Ansible 从多个事实生成 CSV 报告

Ansible Generate CSV report from Multiple Facts

希望你们一切顺利。

我很难从对应于同一主机的多个事实生成 CSV。

更具体地说,我有以下事实:

   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

我的想法是在 CSV 文件中生成一个报告 report.csv,因此我希望使用 Jinja 生成如下内容:

   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

我希望你能帮我解决这个问题。提前谢谢你

例如

    - 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 }}"

给予

  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

下一个选项是在模板中创建结构。下面的任务给出了相同的结果

    - 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 }}"

将模板放入文件中,例如

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

并创建报告

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

给予

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