jamesvader
jamesvader

Reputation: 45

Ansible: Write multiple lines to a file using local_action or another method

I am using the command:

However, when I do it again:

It overwrites the old text with the new text. What I want to do is append to the file instead of replacing the previous text.

I tried adding in a /n to the end of the original string to no avail.

Upvotes: 3

Views: 9082

Answers (2)

balaks80
balaks80

Reputation: 146

Tried multiple posts and this is that finally helped what I wanted to do. Collect various facts and finally output it to a local file for review. Posting it out here, hoping to help someone starting on ansbile :)

---
- name: "Collect host OS Version information for the host"
  vars:
    - output_path: "/tmp"
    - filename: "osinfo_{{date}}.csv"

  vars_prompt:
    - name: input_hostname
      prompt: What is the set of hosts you want connect ? 
      private: no

  hosts: "{{ input_hostname }}"

  tasks:
    - name: CSV Generate output filename
      set_fact: date="{{lookup('pipe','date +%Y%m%d_%H%M%S')}}"
      run_once: true

    - name: CSV - Create file and set the header
      local_action: copy content="Hostname,SID,OSVersion,KernelVersion\n" dest="{{output_path}}/{{filename }}"
      run_once: true

    - name: OS Version info for {{ input_hostname  }} hosts
      set_fact:
        csv_tmp: >
         {{ inventory_hostname }},{{SID}},{{ ansible_distribution_version }},{{ ansible_kernel }}
    
    - name: CSV - Write information into .csv file
      local_action: 
        module: lineinfile
        dest: "{{output_path}}/{{filename }}"
        line:  "{{csv_tmp}}"

    - name: CSV - Blank lines removal
      local_action:
        module: lineinfile
        dest: "{{output_path}}/{{filename }}"
        state: absent
        regex: '^\s*$'

Upvotes: 0

Arbab Nazar
Arbab Nazar

Reputation: 23771

What about the lineinfile module:

local_action:
    module: lineinfile
    dest: "~/ansible/ansible_log.txt"
    line: "The installation failed"
    create: yes
local_action:
    module: lineinfile
    dest: "~/ansible/ansible_log.txt"
    line: "Contact me for assistance"

Upvotes: 5

Related Questions