问题
In Ansible, I have written an Yaml playbook that takes list of host name and the executes command for each host. I have registered a variable for these task and at the end of executing a task I append output of each command to a single file. But every time I try to append to my output file, only the last record is getting persisted.
---
- hosts: list_of_hosts
become_user: some user
vars:
output: []
tasks:
- name: some name
command: some command
register: output
failed_when: "'FAILED' in output"
- debug: msg="{{output | to_nice_json}}"
- local_action: copy content='{{output | to_nice_json}}' dest="/path/to/my/local/file"
I even tried to append using lineinfile using insertafter parameter yet was not successful. Anything that I am missing?
回答1:
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.
回答2:
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
回答3:
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.
来源:https://stackoverflow.com/questions/38363385/ansible-writing-output-from-multiple-task-to-a-single-file