如何在 Ansible 中将文件内容复制到另一个文件而不覆盖第二个文件

Jan*_*uka 2 ansible

我有一个名为的文件a.txt,其中包含以下内容:

123
456
986
231
456
Run Code Online (Sandbox Code Playgroud)

我还有另一个文件,/etc/file2.txt内容如下:

test values
some values
hello world how are you
Run Code Online (Sandbox Code Playgroud)

我想将文件的内容复制a.txt/etc/file2.txt,所以我这样做了:


- name: Copy from a.txt to file2.txt
  copy:
    src: "a.txt"
    dest: "/etc/file2.txt"           

Run Code Online (Sandbox Code Playgroud)

但这会覆盖并替换 file2.txt 中的全部内容

但我希望它是这样的:

test values
some values
hello world how are you
123
456
986
231
456
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

Zei*_*tor 5

那么您就不想复制该文件。a.txt您想要将的内容附加到/etc/file2.txt

从上面的示例来看,a.txt位于您的控制器上,同时/etc/file2.txt位于您的目标上。

第一种快速但肮脏的方法可以直接使用 shell 模块完成:

- name: Unconditionnaly append content of a.txt to /etc/file2.txt
  shell: echo "{{ lookup('file', 'a.txt') }}" >> /etc/file2.txt
Run Code Online (Sandbox Code Playgroud)

现在这有点脏,并且总是会追加内容,即使这已经在之前完成了。另一种可能的方法是使用该blockinfile模块:

- name: Make sure a.txt content is present in /etc/file2.txt
  blockinfile:
    path: /etc/file2.txt
    block: "{{ lookup('file', 'a.txt') }}"
Run Code Online (Sandbox Code Playgroud)

这已经更好了,因为只有文件内容不存在或因为文件内容发生更改才会添加。同时,此方法将在文件中添加块标记,您应该确保它们符合您的要求(有关更多信息,请参阅文档)

我最喜欢的方法肯定是模板。保持a.txt文件不变,在控制器上创建一个文件templates/file2.txt.j2

test values
some values
hello world how are you
{{ lookup('file', 'a.txt') }}
Run Code Online (Sandbox Code Playgroud)

从那里你所需要的就是:

test values
some values
hello world how are you
{{ lookup('file', 'a.txt') }}
Run Code Online (Sandbox Code Playgroud)