I'm writing a playbook that will check the application version on different hosts and write the output to a Ansible variable.

My requirement is I want to output the ansible variable to a file output.logPiece of ansible code to write the ansible variable to output.log.

What the problem is the variable is written to the file only for the last host in the hosts inventory, But i want for all the hosts to be appended in the output.log file

Image ref

  • 3
    Please, don't post screenshots of text you could just copy&paste. Just copy&paste the text. Sep 10, 2021 at 12:53

2 Answers 2


Delegate the task to localhost and use lineinfile to add it to your file:

- name: store info
    path: "/tmp/out.log"
    regexp: "\\s{{ inventory_hostname }}$"
    line: "{{ java_version.msg }} {{ inventory_hostname }}"
    create: yes
  delegate_to: localhost

The regexp attribute will make sure that old entries get replaced when you run the playbook again and the version has changed.


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.

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

  - 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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .