How to copy file content to another file in Ansible without overwriting the second file

Viewed 2992

I have a file called a.txt which has following contents:

123
456
986
231
456

And I have another file in the /etc/file2.txt and has below content:

test values
some values
hello world how are you

And I want to copy the content of file a.txt to /etc/file2.txt, so I did this:


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

But this Overrides and replaces the whole contents in the file2.txt

But I want it to be like this:

test values
some values
hello world how are you
123
456
986
231
456

Can someone give me a help?

1 Answers

Then you don't want to copy the file. You want to append the content of a.txt to /etc/file2.txt.

From your above example, a.txt is on your controller while /etc/file2.txt is on your target.

A first quick and dirty approach can be done directly with the shell module:

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

Now this is kind of dirty and will always append the content, even if this was already done earlier. An other possible approach is to use the blockinfile module:

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

This is already better as the content of the file will be added only if not already there or because it changed. Meanwhile, this method will add block markers in the file and you should make sure they are comptible with your requirements (see the documentation for more info)

My prefered method would definitely be a template. Keeping the a.txt file as it is, create on your controller a file templates/file2.txt.j2:

test values
some values
hello world how are you
{{ lookup('file', 'a.txt') }}

From there all you need is:

- name: Make sure `/etc/file2.txt` is aligned to our template
  template:
    src: file2.txt.j2
    dest: /etc/file2.txt
Related