Ansible writing output from multiple task to a single file

心不动则不痛 提交于 2019-12-06 09:54:23

You can try something like this:

- name: dummy
  hosts: myhosts
  serial: 1
  tasks:
    - name: create file
      file:
        dest: /tmp/foo
        state: touch
      delegate_to: localhost

    - name: run cmd
      shell: echo "{{ inventory_hostname }}"
      register: op

    - name: append
      lineinfile:
        dest: /tmp/foo
        line: "{{ op }}"
        insertafter: EOF
      delegate_to: localhost

I have used serial: 1 as I am not sure if lineinfile tasks running in parallel will garble the output file.

Ansible doc recommend use copy:

- name: get jstack                                                                        
  shell: "/usr/lib/jvm/java/bin/jstack -l {{PID_JAVA_APP}}"                                                             
  args:                                                                                                      
    executable: /bin/bash
  register: jstackOut                                           

- name: write jstack                                                                                
  copy:                                                                                              
     content: "{{jstackOut.stdout}}" 
     dest: "tmp/jstack.txt"

If you want write local file, add this:

     delegate_to: localhost 

I think it may help you... This playbook check Basic hardware information for LINUX systems and save output in a single file.

- name: LINUX CONFIGURATION CHECK
  gather_facts: false
  hosts: linux
  tasks:
    - name: Checking IP Address
      shell: hostname -I
      register: ip
    - name: Checking Mac Address
      shell: lshw -class network | grep -E 'serial:' | cut -d " " -f9
      register: mac
    - name: Checking OS Version
      shell: cat /etc/*release | grep PR | cut -d "\"" -f2
      register: os

    - local_action: copy content={{ip.stdout}} dest=/etc/ansible/output.txt

    - name: Append
      lineinfile:
        dest: /etc/ansible/finalout.txt
        line: "{{mac.stdout}}{{os.stdout}}"
        insertafter: EOF
      delegate_to: localhost

The Local action copy the answer and save in a file. The append insert output to EOF - end of the file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!