Score:0

Ansible task output to a file in ansible server

sd flag

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

in flag
Please, don't post screenshots of text you could just copy&paste. Just copy&paste the text.
Score:2
in flag

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

- name: store info
  lineinfile: 
    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.

Score:2
cn flag

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.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.