如何从ansible事实获取json输出到本地文件?

时间:2019-10-14 08:34:30

标签: ansible

我需要获取带有一些类似这样的主机事实的json输出:

{
"DBADOKUVERSION": 5.0,
"DATE": "14102019 0101",
"HOSTNAME": "host1",
"DOMAIN": ""no domain name",
"HW_PLATFORM": "x86_64",
"SERVER_TYPE": "virtual",
"CPU_TYPE": "Intel Xeon Processor (Skylake, IBRS)",
"CPU_COUNT": "1",
"CORE_COUNT": "8",
"THREAD_COUNT": "8",
"MEMORY": "32005120 kB",
"OS": "Linux",
"OS_VERSION": "CentOS",
"OS_UPTIME": "6473126",
"RELEASE": "7.6.1810",
"RELEASE_PATCHLEVEL": "NOT READY"
}

目前,我可以使用“ messy”模板:

{% if ansible_system == 'Linux' %}
{
"DBADOKUVERSION": 5.0,
"DATE": "{{ ansible_date_time.day }}{{ ansible_date_time.month }}{{ ansible_date_time.year }} {{ ansible_date_time.hour }}{{ ansible_date_time.minute }}",
"HOSTNAME": "{{ ansible_hostname }}",
"DOMAIN": ""{% if ansible_domain == '' %}no domain name{% else %}{{ ansible_domain }}{% endif %}",
"HW_PLATFORM": "{{ ansible_architecture }}",
"SERVER_TYPE": "{% if ansible_virtualization_role == 'guest' %}virtual{% else %}physical{% endif %}",
"CPU_TYPE": "{{ansible_processor[2]}}",
"CPU_COUNT": "{{ansible_processor_count}}",
"CORE_COUNT": "{{ansible_processor_cores}}",
"THREAD_COUNT": "{{ansible_processor_vcpus}}",
"MEMORY": "{{ansible_memtotal_mb * 1024}} kB",
"OS": "{{ansible_system}}",
"OS_VERSION": "{{ansible_distribution}}",
"OS_UPTIME": "{{ansible_uptime_seconds}}",
"RELEASE": "{{ansible_distribution_version}}",
"RELEASE_PATCHLEVEL": "NOT READY"
}
{% elif ansible_system == 'SunOS' %}
{
"DBADOKUVERSION": 5.0,
"DATE": "{{ ansible_date_time.day }}{{ ansible_date_time.month }}{{ ansible_date_time.year }} {{ ansible_date_time.hour }}{{ ansible_date_time.minute }}",
"HOSTNAME": "{{ ansible_hostname }}",
"DOMAIN": ""{% if ansible_domain == '' %}no domain name{% else %}{{ ansible_domain }}{% endif %}",
"HW_PLATFORM": "{{ ansible_architecture }}",
"SERVER_TYPE": "Solaris",
"CPU_TYPE": "{{ansible_processor[0]}}",
"CPU_COUNT": "{{ansible_processor_count}}",
"CORE_COUNT": "{{ansible_processor_cores}}",
"THREAD_COUNT": "{% if ansible_processor_vcpus is undefined %}null{% else %}{{ansible_processor_vcpus}}{% endif %}", 
"MEMORY": "{{ansible_memtotal_mb * 1024}} kB",
"OS": "{{ansible_system}}",
"OS_VERSION": "{{ansible_distribution}}",
"OS_UPTIME": "{{ansible_uptime_seconds}}",
"RELEASE": "{{ansible_distribution_version}}",
"RELEASE_PATCHLEVEL": "NOT READY"
}
{% else %}
Not Linux or SunOS
{% endif %}

用于将模板获取到Ansible本地主机的剧本:

---

- name: "Custom facts"
  hosts: "solaris"
  gather_facts: yes
  remote_user: root

  tasks:

  - name: "Get facts."
    template:
       src: template.j2
       dest: "/tmp/{{ inventory_hostname }}.json"
    delegate_to: localhost

1)您是否知道更聪明的解决方案,以获取没有上述模板和条件的json输出?

2)如何在没有模板的情况下将json输出写入某些json文件?

0 个答案:

没有答案