Install a facts script to /etc/ansible/facts.d/java.fact
on remote hosts and make it executable. Escaping JSON to print on standard out is little ugly. Also ugly, parsing a version "number" out of java -version
. Although you might be collecting version in a different way, adjust the script as necessary.
#!/bin/sh
JAVA_VERSION=$(java -version 2>&1 | grep version | cut -d '"' -f 2)
printf "{\"java_version\": \"${JAVA_VERSION}\"}\n"
Write a Jinja template to print the version number lines in the desired format. Say the file is templates/javaversionreport.txt
- groups is a magic dict of inventory_hostname indexed by group
- hostvars is a magic dict with other hosts' variables
- ansible_local is the "local facts" variable
- java is from the
java.fact
file name
{% for host in groups['hosts'] %}
{{ hostvars[host].ansible_local.java.java_version }} {{ host }}
{% endfor %}
And plays to collect facts and write the report. Adjust the hosts pattern as desired.
---
- hosts: hosts
gather_facts: True
fact_path: /etc/ansible/facts.d
- hosts: localhost
gather_facts: False
tasks:
- template:
src: javaversionreport.txt
dest: /tmp/out.log
One template render runs faster than rewriting files with linefinfile. Although fact gathering can be slow. Also, Jinja templates can be written any format you like.