Ansible 将多个任务的输出写入单个文件
在 Ansible 中,我编写了一个 Yaml 剧本,其中包含主机名列表和每个主机的执行命令.我已经为这些任务注册了一个变量,并在执行任务结束时将每个命令的输出附加到一个文件中.但是每次我尝试附加到我的输出文件时,只有最后一条记录被持久化.
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"
我什至尝试使用 insertafter 参数使用 lineinfile 进行追加,但没有成功.有什么我遗漏的吗?
I even tried to append using lineinfile using insertafter parameter yet was not successful. Anything that I am missing?
你可以试试这样的:
- 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
我使用了 serial: 1
因为我不确定 lineinfile
并行运行的任务是否会导致输出文件出现乱码.
I have used serial: 1
as I am not sure if lineinfile
tasks running in parallel will garble the output file.